Generating Unique Random Numbers in Java

后端 未结 21 2534
不思量自难忘°
不思量自难忘° 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:57

    Choose n unique random numbers from 0 to m-1.

    int[] uniqueRand(int n, int m){
        Random rand = new Random();
        int[] r = new int[n];
        int[] result = new int[n];
        for(int i = 0; i < n; i++){
            r[i] = rand.nextInt(m-i);
            result[i] = r[i];
            for(int j = i-1; j >= 0; j--){
                if(result[i] >= r[j])
                    result[i]++;
            }
        }
        return result;
    }
    

    Imagine a list containing numbers from 0 to m-1. To choose the first number, we simply use rand.nextInt(m). Then remove the number from the list. Now there remains m-1 numbers, so we call rand.nextInt(m-1). The number we get represents the position in the list. If it is less than the first number, then it is the second number, since the part of list prior to the first number wasn't changed by the removal of the first number. If the position is greater than or equal to the first number, the second number is position+1. Do some further derivation, you can get this algorithm.

    Explanation

    This algorithm has O(n^2) complexity. So it is good for generating small amount of unique numbers from a large set. While the shuffle based algorithm need at least O(m) to do the shuffle.

    Also shuffle based algorithm need memory to store every possible outcome to do the shuffle, this algorithm doesn’t need.

提交回复
热议问题