AvP - 1 year ago 47

Java Question

`public static int[] uniqueRandomElements (int size) {`

int[] a = new int[size];

for (int i = 0; i < size; i++) {

a[i] = (int)(Math.random()*10);

for (int j = 0; j < i; j++) {

if (a[i] == a[j]) {

a[j] = (int)(Math.random()*10);

}

}

}

for (int i = 0; i < a.length; i++) {

System.out.print(a[i]+" ");

}

System.out.println();

return a;

}

I have a method above which should generate an array of random elements that the user specifies. The randomly generated integers should be between 0 and 10 inclusive. I am able to generate random integers but the problem I have is checking for uniqueness. My attempt to check for uniqueness is in my code above but the array still contains duplicates of integers. What am I doing wrong and could someone give me a hint?

Answer Source

```
for (int i = 0; i < size; i++) {
a[i] = (int)(Math.random()*10);
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
a[j] = (int)(Math.random()*10); //What's this! Another random number!
}
}
}
```

You do find the duplicate values. However, you replace it with another random number that may be a duplicate. Instead, try this:

```
for (int i = 0; i < size; i++) {
a[i] = (int)(Math.random()*10);//note, this generates numbers from [0,9]
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
i--; //if a[i] is a duplicate of a[j], then run the outer loop on i again
break;
}
}
}
```

However, this method is inefficient. I recommend making a list of numbers, then randomizing it:

```
ArrayList<Integer> a = new ArrayList<>(11);
for (int i = 0; i <= 10; i++){ //to generate from 0-10 inclusive.
//For 0-9 inclusive, remove the = on the <=
a.add(i);
}
Collections.shuffle(a);
a = a.sublist(0,4);
//turn into array
```

Or you could do this:

```
ArrayList<Integer> list = new ArrayList<>(11);
for (int i = 0; i <= 10; i++){
list.add(i);
}
int[] a = new int[size];
for (int count = 0; count < size; count++){
a[count] = list.remove((int)(Math.random() * list.size()));
}
```