Generating Unique Random Numbers in Java

后端 未结 21 2545
不思量自难忘°
不思量自难忘° 2020-11-21 07:45

I\'m trying to get random numbers between 0 and 100. But I want them to be unique, not repeated in a sequence. For example if I got 5 numbers, they should be 82,12,53,64,32

21条回答
  •  既然无缘
    2020-11-21 07:51

    One clever way to do this is to use exponents of a primitive element in modulus.

    For example, 2 is a primitive root mod 101, meaning that the powers of 2 mod 101 give you a non-repeating sequence that sees every number from 1 to 100 inclusive:

    2^0 mod 101 = 1
    2^1 mod 101 = 2
    2^2 mod 101 = 4
    ...
    2^50 mod 101 = 100
    2^51 mod 101 = 99
    2^52 mod 101 = 97
    ...
    2^100 mod 101 = 1
    

    In Java code, you would write:

    void randInts() {
    int num=1;
    for (int ii=0; ii<101; ii++) {
        System.out.println(num);
        num= (num*2) % 101;
        }
    }
    

    Finding a primitive root for a specific modulus can be tricky, but Maple's "primroot" function will do this for you.

提交回复
热议问题