for (int x = 0 ; x < chosenQ.length ; x++)
{
chosenQ [x] = r.nextInt (9);
c.println (chosenQ [x]);
}
This generates 5 ints between 0 and 9. How do i make it so it will not have duplicate ints when generating it?
for (int x = 0 ; x < chosenQ.length ; x++)
{
chosenQ [x] = r.nextInt (9);
c.println (chosenQ [x]);
}
This generates 5 ints between 0 and 9. How do i make it so it will not have duplicate ints when generating it?
In pseudo code
array = [0, 1, ..., 9]
array.shuffle.take(5)
You'll have to keep a record of which numbers were chosen already.
One way you can do that is by storing the values in a boolean array where all values are initialized to false
. When a random value is generated, the element at that index is set to true
. Then, for each generated number, you can simply check if the element at that index is true
or false
.
For example,
// array of booleans initialized to false
boolean[] array = new boolean[chosenQ.length];
for (int x = 0 ; x < chosenQ.length ; x++)
{
int i = r.nextInt(9);
// check if value was chosen already
while (array[i] == true)
i = r.nextInt(9);
// set generated value's index in array to true
array[i] = true;
chosenQ[x] = i;
c.println(chosenQ[x]);
}