Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Java by (10.2k points)

I've been using Random (java.util.Random) to shuffle a deck of 52 cards. There are 52! (8.0658175e+67) possibilities. Yet, I've found out that the seed for java.util.Random is a long, which is much smaller at 2^64 (1.8446744e+19).

From here, I'm suspicious whether java.util.Random is really that random; is it actually capable of generating all 52! possibilities?

If not, how can I reliably generate a better random sequence that can produce all 52! possibilities?

1 Answer

0 votes
by (46k points)

Your summary is correct: seeding a pseudo-random number generator among any specific seed must yield the same sequence following a shuffle, limiting the number of permutations that you could obtain to 264. This assertion is easy to verify experimentally by calling Collection.shuffle twice, passing a Random object initialized with the corresponding seed, and observing that the two random shuffles are identical.

A solution to this, then, is to use a random character generator that allows for a larger seed. Java provides SecureRandom class that could be initialized with byte[] collection of practically unlimited size. You could then pass an instance of SecureRandom to Collections.shuffle to complete the task:

byte seed[] = new byte[...];

Random rnd = new SecureRandom(seed);

Collections.shuffle(deck, rnd);

Related questions

Browse Categories