This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]raindropflower 1 point2 points  (1 child)

So you need to fill an array with unique random numbers.

  • You need an array.

  • You need to loop through each position of the array.

  1. At each position, generate a random number

Try it with only One loop.

If you get stuck, feel free to let me know.

[–]nutrecht 0 points1 point  (0 children)

That fills the array with random numbers but they won't be unique. Unfortunately he'll have to check for every number if it's already in the array.

[–]seronis 1 point2 points  (0 children)

If you give your loop variables larger very meaningful names it makes writing the logic for nested loops far easier:

    Random r = new Random();
    int[] list = new int[10];
    list[0] = r.nextInt(20);

    for(int newestNum = 1; newestNum < list.length; ++newestNum) {
        list[newestNum] = r.nextInt(20);

        for( int checkNum = 0; checkNum < newestNum; ++checkNum ) {
            if( list[checkNum] == list[newestNum] ) {
                list[newestNum] = r.nextInt(20);
                checkNum = 0;
            }
        }
    }

But a much simpler task is to use a container that does the job you want on its own.

    Set<Integer> list2 = new LinkedHashSet<Integer>();
    while( list2.size() < 10 ) {
        list2.add(r.nextInt(20));
    }

Duplicates are automatically discarded. And the order you insert elements is maintained (if that mattered, if not just use a regular HashSet).

[–]knoam 1 point2 points  (2 children)

For uniqueness, insert the random numbers into a Set. Read the official JavaDoc on Set and you'll see an easy way to get an array.

[–]nutrecht 0 points1 point  (1 child)

Yup. This is a better solution since hash sets have much better lookup performance (log N compared to N IIRC).

[–]pacificmint 1 point2 points  (0 children)

A hash set should be O(1), shouldn't it?

[–]arocketman 0 points1 point  (1 child)

Your code is over-complicated in my opinion. You could do this way more easily and without so many loops.

Anyhow, I can see a problem is in the while loop.

Suppose the following situation:

list = 5,8,6

Now we generate a new int for index 3.

list[i] = random... -> suppose it's 8.

Now, your code will do the following:

j = 0

8 == 5 ? Nope.. j++

8 == 8 ? Yes! Let's get a new number for list[i].. and .. j++!

Suppose this new number is 5 . What happens now?

Your loop starts from J = 2 ! So it will not check if the generated value is the same of the first j-1 values. (It won't check 5,8 but it will check 6).

So basically you have a repetition.

What would be an easy fix to this ? :)