What is the best algorithm to shuffle cards? [closed]

落花浮王杯 提交于 2019-12-13 12:52:32

问题


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]


来源:https://stackoverflow.com/questions/40057647/what-is-the-best-algorithm-to-shuffle-cards

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!