-3

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?

Kaidul
  • 15,409
  • 15
  • 81
  • 150
Tal Avissar
  • 10,088
  • 6
  • 45
  • 70
  • 2
    How do you define `"the best shuffled pack of cards"`? – Pang Oct 15 '16 at 10:04
  • Define "best". Also, this question is either primarily opinion-based, or asking for suggestions of 3rd party content, both of which are off-topic here on Stack Overflow. – Lasse V. Karlsen Oct 15 '16 at 10:05
  • minimum steps and the distances between cards, obviously some types of shuffles are superior to others. – Tal Avissar Oct 15 '16 at 10:05
  • 1
    I'm voting to close this question as off-topic because of the tenuous connection between real-world card shuffling methods and programming or computer science. – Paul Hankin Oct 15 '16 at 10:11
  • 1
    See e.g., https://en.wikipedia.org/wiki/Random_permutation – Andreas H. Oct 15 '16 at 10:15
  • 2
    If you are looking for an efficient randomization algorithm this is one of the best: [https://en.wikipedia.org/wiki/Fisher–Yates_shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle). – Renzo Oct 15 '16 at 10:15
  • 2
    @TalAvissar So with MORE distance between adjacent cards and minimum steps makes one shuffle combination better than other? – Kaidul Oct 16 '16 at 04:02

2 Answers2

9

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 these N! permutations is equally likely to be returned. Time complexity is O(N).

Kaidul
  • 15,409
  • 15
  • 81
  • 150
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]
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
  • 3
    Looks right. The important point is that you swap with a random number on i to N, not 0 to N as you might first think. Swapping on 0 to N gives a strange, non-uniform distribution. – Malcolm McLean Oct 15 '16 at 10:40