Generating unique random number in java [duplicate

2019-06-09 20:00发布

This question already has an answer here:

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]);

        }

2条回答
Lonely孤独者°
2楼-- · 2019-06-09 20:10

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.

查看更多
相关推荐>>
3楼-- · 2019-06-09 20:19
  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

查看更多
登录 后发表回答