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

前端 未结 9 1961
-上瘾入骨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条回答
  •  旧时难觅i
    2020-12-22 16:11

    In general, a pseudorandom number generator (PRNG) can't choose from among all permutations of a 52-item list if its maximum cycle length is less than 226 bits.

    java.util.Random implements an algorithm with a modulus of 248 and a maximum cycle length of only 48 bits, so much less than the 226 bits I referred to. You will need to use another PRNG with a bigger cycle length, specifically one with a maximum cycle length of 52 factorial or greater.

    See also "Shuffling" in my article on random number generators.

    This consideration is independent of the nature of the PRNG; it applies equally to cryptographic and noncryptographic PRNGs (of course, noncryptographic PRNGs are inappropriate whenever information security is involved).


    Although java.security.SecureRandom allows seeds of unlimited length to be passed in, the SecureRandom implementation could use an underlying PRNG (e.g., "SHA1PRNG" or "DRBG"). And it depends on that PRNG's maximum cycle length whether it's capable of choosing from among 52 factorial permutations.

提交回复
热议问题