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

后端 未结 5 1583
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  猫巷女王i
    2020-12-17 06:51

    This is code is very efficient with the CPU at the cost of memory. Each potiental value cost sizeof(int) * maxValue. An unsigned integer will work up to 65535 as a max. long can be used at the cost of a lot of memory 2000 bytes for 1000 values of 16 bit integers.

    The whole purpose of the array is to say have you used this value before or not 1 = yes 'anything else = no 'The while loop will keep generating random numbers until a unique value is found. 'after a good random value is found it marks it as used and then returns it. 'Be careful of the scope of variable a as if it goes out of scope your array could erased. ' I have used this in c and it works. ' may take a bit of brushing up to get it working in Java.

    unsigned int a(1000);
    
    public int getRandomNumber(int maxValue) {
      unsigned int rand;
    
      while(a(rand)==1) {
        rand=random.nextInt(maxValue);
        if (a(rand)!=1) { a(rand)=1; return rand;}
      }
    
    }
    

提交回复
热议问题