Is java.util.Random really that random? How can I generate 52! (factorial) possible sequences?

前端 未结 9 1955
-上瘾入骨i
-上瘾入骨i 2020-12-22 15:56

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

9条回答
  •  攒了一身酷
    2020-12-22 16:26

    Your analysis is correct: seeding a pseudo-random number generator with any specific seed must yield the same sequence after 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 same seed, and observing that the two random shuffles are identical.

    A solution to this, then, is to use a random number generator that allows for a larger seed. Java provides SecureRandom class that could be initialized with byte[] array of virtually 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);
    

提交回复
热议问题