简体   繁体   中英

Generate a List of Unique Random Numbers

So, I have a random number generator, where it generates 10 numbers between 1 and whatever the user inputs as the maximum. It worked well, but I want to make it so it doesn't generate duplicate numbers. So, if it generates a 5, none of the other numbers can be 5.

You can try rejection sampling. Begin with an empty set. Generate a number, if it is in the set, try again. That is to say keep picking until you find a number not in the set. Once you find a new number add it to the set and then return it to the user.

Of course if a large amount of numbers have been generated, say k and the upper bound is n, then the time to get a new number follows a geometric distribution (with success probability (nk)/n), so the expected number of samplings required before you find a unique number is n/(nk).

If you have a small maximum, you can use Collection.shuffle() a list of unique values. From this you can select 10 elements.

You are not the first to ask this question. See https://crypto.stackexchange.com/questions/1379/how-to-generate-a-list-of-unique-random-strings for a general answer.

In order to ensure that the number is not a duplicate, store the found numbers in Java SET so that adds only if there is no duplicate inside it.

Algorith for random generation can be something like:

take the system time as your seed value 
use this to get the random numbers
suppose user says number between 1-100
so take system milliseconds%100 so time always  changes so maximum probability that you get random numbers.

So, always take the seed value mod(%) your upper bound in this case its 100.

int i = 0, r = 0;
    boolean ch = true;
    int[] list = new int[num];
    while (i < num)
    {
        r = rnd.nextInt(num);
        ch = true;
        for (int j = 0; j < i; j++)
            if (r == list[j])
            {
                ch = false;
                break;
            }
        if (ch)
        {
            list[i] = r;
            i++;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM