-->

What is the best algorithm to shuffle cards? [clos

2020-08-09 04:57发布

问题:

Given a finite set of N cards, what is the best way (algorithm) to shuffle the cards so I will have the best shuffled pack of cards with minimum steps to get maximum random permutations?

What is the best solution in minimum steps?

回答1:

Use Fisher Yates algorithm. Many programming languages use variant of this algorithm to shuffle elements of finite set. This is the pseudo code of Fisher Yates algorithm (optimised version by Richard Durstenfeld):

-- To shuffle an array a of n elements (indices 0..N-1):
for i from N−1 downto 1 do
     j ← random integer such that 0 ≤ j ≤ i
     exchange a[j] and a[i]

This algorithm ensures uniform distribution. For N cards, there are N! shuffled combinations possible. Here any of N! permutations is equally likely to be returned. Time complexity is O(N).



回答2:

This is the classic (which I believe is provably the best, using the exact number of bits needed for len(x) factorial permutations):

def shuffle(x):
    """Shuffle list x in place, and return None."""
    for i in reversed(range(1, len(x))):
        # pick an element in x[:i+1] with which to exchange x[i]
        j = int(random() * (i+1))
        x[i], x[j] = x[j], x[i]