-3
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?

Rob
  • 26,989
  • 16
  • 82
  • 98
  • 1
    You tagged this question as 'javascript'... should be 'java'. – quarterpi Dec 23 '16 at 00:47
  • small set of possible values, and you want a significant amount of these values without repetition: create an Array of all possible values, shuffle it, and take the first n *(5)* values – Thomas Dec 23 '16 at 00:51

2 Answers2

1
  • Create an array with 10 elements from 0 to 9
  • Shuffle the array
  • Take the first five elements

In pseudo code

array = [0, 1, ..., 9]
array.shuffle.take(5)
akuhn
  • 27,477
  • 2
  • 76
  • 91
0

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]);
}
Micros
  • 145
  • 1
  • 8
  • this is a pretty inefficient approach, and absolutely not suitable for bigger sets of values – Thomas Dec 23 '16 at 01:02
  • For this to be a memory efficient approach, you should use a [`BitSet`](https://docs.oracle.com/javase/8/docs/api/java/util/BitSet.html) instead of a boolean array. – 4castle Dec 23 '16 at 01:07