Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 3 years ago.
Improve this question
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?
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)
.
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]