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

前端 未结 9 1975
-上瘾入骨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:23

    A very simple algorithm is to apply SHA-256 to a sequence of integers incrementing from 0 upwards. (A salt can be appended if desired to "get a different sequence".) If we assume that the output of SHA-256 is "as good as" uniformly distributed integers between 0 and 2256 - 1 then we have enough entropy for the task.

    To get a permutation from the output of SHA256 (when expressed as an integer) one simply needs to reduce it modulo 52, 51, 50... as in this pseudocode:

    deck = [0..52]
    shuffled = []
    r = SHA256(i)
    
    while deck.size > 0:
        pick = r % deck.size
        r = floor(r / deck.size)
    
        shuffled.append(deck[pick])
        delete deck[pick]
    

提交回复
热议问题