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);
you can use boolean array to fill the true if value taken else set navigate through boolean array to get value as per given below
With Java 8+ you can use the
ints
method ofRandom
to get anIntStream
of random values thendistinct
andlimit
to reduce the stream to a number of unique random values.Random
also has methods which createLongStream
s andDoubleStream
s if you need those instead.If you want all (or a large amount) of the numbers in a range in a random order it might be more efficient to add all of the numbers to a list, shuffle it, and take the first n because the above example is currently implemented by generating random numbers in the range requested and passing them through a set (similarly to Rob Kielty's answer), which may require generating many more than the amount passed to limit because the probability of a generating a new unique number decreases with each one found. Here's an example of the other way:
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:
In Java code, you would write:
Finding a primitive root for a specific modulus can be tricky, but Maple's "primroot" function will do this for you.
Check this
Use
Collections.shuffle()
on all 100 numbers and select the first five, as shown here.I re-factored Anand's answer to make use not only of the unique properties of a Set but also use the boolean false returned by the
set.add()
when an add to the set fails.