How to be sure that random numbers are unique and not duplicated?

后端 未结 5 1589
隐瞒了意图╮
隐瞒了意图╮ 2020-12-17 06:23

I have a simple code which generates random numbers

SecureRandom random = new SecureRandom();
...
public int getRandomNumber(int maxValue) {
    return rando         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 07:17

    A random sequence does not mean that all values are unique. The sequence 1,1,1,1 is exactly as likely as the sequence 712,4,22,424.

    In other words, if you want to be guaranteed a sequence of unique numbers, generate 10 of them at once, check for the uniqueness condition of your choice and store them, then pick a number from that list instead of generating a random number in your 10 places.

提交回复
热议问题