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 and not 82,12,53,12,32 I used this, but it generates same numbers in a sequence.
Random rand = new Random();
selected = rand.nextInt(100);
I have made this like that.
Here is a simple implementation. This will print 3 unique random numbers from the range 1-10.
The first part of the fix with the original approach, as Mark Byers pointed out in an answer now deleted, is to use only a single
Random
instance.That is what is causing the numbers to be identical. A
Random
instance is seeded by the current time in milliseconds. For a particular seed value, the 'random' instance will return the exact same sequence of pseudo random numbers.I have easy solution for this problem, With this we can easily generate n number of unique random numbers, Its just logic anyone can use it in any language.
Choose n unique random numbers from 0 to m-1.
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 callrand.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.I feel like this method is worth mentioning.
try this out