How do you generate random numbers in Java without duplicate? Thanks.

This question is already asked.Check this

There are many ways to generate unique random numbers.I am discussing two of them below:-

  • Write the numbers sequentially in a list structure.
    Shuffle it.
    Take the first 'n'.
    This uses only a single Random instance.
  • Another option

Call Random rand = new Random();rand.nextInt(78)
and store value in Set.If added successfully(means unique as set doesnot support duplicacy) means it is unique.
Check the size,if it is less than 3 then keep on adding.

Also, if you want to generate a large amount of random numbers (so that duplicates would happen often) and you don't have a list of elements to choose from, or don't want to copy your list so you can shuffle it, then you can also choose n without duplicates from a set of m by iterating like this:

java.util.Random r = new java.util.Random();
for(int i = 0; i < m; i++) {
    if(r.nextInt(m - i) < n) {
        choose i;
        n--;
    }
}

And do realise that as soon as you filter the numbers to (for example) not have duplicates they're no longer random.

This article has been dead for over six months. Start a new discussion instead.