0

I want to generate random number from 1 to 9 and i want them to be unique. This is the code i have written which gives me 9 different numbers from 1 to 9 but I have no clue on generating unique number.

 int data[] = new int[10];
      for(int i = 0; i < data.length; i++) {
            Random randomGenerator = new Random();

            data[i] = randomGenerator.nextInt(10);
          System.out.println(data[i]);

        }
Calum
  • 1,889
  • 2
  • 18
  • 36
MR AND
  • 376
  • 7
  • 29
  • 1
    Look at "Related" list on right hand side. How do you explain that? – BalusC Sep 20 '15 at 15:08
  • Have a look at my question : http://stackoverflow.com/questions/32233896/java-securerandom-nextint-vs-nextgaussian which may be useful – Ravindra babu Sep 20 '15 at 15:12
  • I would suggest to use different solution : 1) Store 1 to 9 numbers in an array 2) Use Math.random(10) to get one of these 10 numbers from array. – Ravindra babu Sep 20 '15 at 15:13

2 Answers2

3

Fill a List<Integer> list with 1..9 and then:

Collections.shuffle(list);

Note that to fill an array of 10, you'll have to have one duplicate.

laune
  • 31,114
  • 3
  • 29
  • 42
1
  1. Store 1 to 9 numbers in an Array.

  2. Generate random number between 1 to 9 as position and return array[position-1] to get the value

  3. Once you use a number in array, mark the value as -1.

  4. If value in array is -1, get the random number again

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
  • And how do you guarantee to avoid getting the same number twice? How is this any different from generating random numbers in the range 1..9 (0..8)? – laune Sep 20 '15 at 15:18
  • whenever you get a number, use it and make the value in that location as -1. Have a loop to draw random number again if value of array element is -1 – Ravindra babu Sep 20 '15 at 15:21