Card Shuffling
How many shuffles does it take to mix a deck of cards? The famous answer, from work by Bayer and Diaconis on the riffle shuffle, is "about seven". Shuffling is a beautiful application of permutations and probability, and it matters in software too: a subtly wrong shuffle is a real bug that has shipped in real products.
The correct algorithm: Fisher–Yates
To shuffle a list uniformly, go from the last position down, swapping each position with a uniformly chosen position at or below it:
import random
from collections import Counter
def fisher_yates(a, rng):
a = list(a)
for i in range(len(a) - 1, 0, -1):
j = rng.randint(0, i) # 0 <= j <= i
a[i], a[j] = a[j], a[i]
return a
def naive(a, rng):
a = list(a)
for i in range(len(a)):
j = rng.randint(0, len(a) - 1) # BUG: j over the whole list
a[i], a[j] = a[j], a[i]
return a
rng = random.Random(1)
trials = 60_000
for name, f in [("Fisher-Yates", fisher_yates), ("naive", naive)]:
c = Counter("".join(f("abc", rng)) for _ in range(trials))
print(f"{name:12s}", {k: round(v / trials, 3) for k, v in sorted(c.items())})Fisher-Yates {'abc': 0.165, 'acb': 0.167, 'bac': 0.166, 'bca': 0.166, 'cab': 0.167, 'cba': 0.169}
naive {'abc': 0.149, 'acb': 0.185, 'bac': 0.185, 'bca': 0.185, 'cab': 0.148, 'cba': 0.149}
Fisher–Yates makes equally likely choice sequences, one per permutation: uniform. The naive version makes equally likely choice sequences; for that is 27, which cannot be split evenly among permutations, so some orders must be more likely. The simulation shows the bias (each should be ).
Riffle shuffles
A riffle shuffle cuts the deck into two packets and interleaves them. The Gilbert–Shannon–Reeds model makes this precise: cut at a binomially distributed position (each card goes to the top packet with probability ), then drop cards one at a time from the bottom of the packets, choosing a packet with probability proportional to its current size.
How do we measure mixing? One simple statistic is the number of rising sequences: maximal runs of consecutive card values that appear in increasing order of position. A perfectly ordered deck has 1; one riffle produces at most 2; riffles at most . A uniformly random deck has about . Until is comparable to , the deck is visibly not random.
import random
def riffle(deck, rng):
n = len(deck)
cut = sum(rng.random() < 0.5 for _ in range(n))
top, bottom = deck[:cut], deck[cut:]
out = []
while top or bottom:
if rng.random() < len(top) / (len(top) + len(bottom)):
out.append(top.pop(0))
else:
out.append(bottom.pop(0))
return out
def rising_sequences(deck):
pos = {card: i for i, card in enumerate(deck)}
return 1 + sum(pos[c + 1] < pos[c] for c in range(len(deck) - 1))
rng = random.Random(4)
for k in [1, 2, 3, 4, 5, 6, 7, 8, 10]:
total = 0
for _ in range(300):
deck = list(range(52))
for _ in range(k):
deck = riffle(deck, rng)
total += rising_sequences(deck)
print(f"{k:2d} riffles: average rising sequences {total / 300:.2f}")
uniform = []
for _ in range(300):
d = list(range(52))
rng.shuffle(d)
uniform.append(rising_sequences(d))
print("uniform deck:", round(sum(uniform) / 300, 2)) 1 riffles: average rising sequences 2.00
2 riffles: average rising sequences 4.00
3 riffles: average rising sequences 7.94
4 riffles: average rising sequences 14.01
5 riffles: average rising sequences 19.67
6 riffles: average rising sequences 22.92
7 riffles: average rising sequences 24.69
8 riffles: average rising sequences 25.67
10 riffles: average rising sequences 26.30
uniform deck: 26.56
The average climbs and then levels off at the uniform value of around seven riffles. Bayer and Diaconis computed the exact total variation distance to uniform for 52 cards: it stays near 1 for up to 4 shuffles and then drops sharply between 5 and 8. This sudden drop, the cutoff phenomenon, is typical of Markov chains on large state spaces (Markov Chains).
How many orders are there?
. A shuffle driven by a 32-bit seed can reach at most of them, a vanishing fraction. For card games played for money, the seed space must be large (and secret), or players can deduce the deck from the first few cards.
import math
print(f"52! = {math.factorial(52):.3e}")
print("bits needed to index every order:", math.ceil(math.log2(math.factorial(52))))
print(f"fraction reachable from 32-bit seeds: {2 ** 32 / math.factorial(52):.1e}")52! = 8.066e+67
bits needed to index every order: 226
fraction reachable from 32-bit seeds: 5.3e-59
In software
Use the library: Python's random.shuffle and numpy.random.Generator.permutation implement Fisher–Yates. When shuffling for security (cards for money, cryptographic protocols), use a cryptographic generator such as secrets.SystemRandom().shuffle. Sorting by a random comparator (sort(() => Math.random() - 0.5) in JavaScript) is another classic biased shuffle.
Exercises
Exercise 1: Naive bias by hand
In the naive shuffle of 3 items, how many of the 27 choice sequences produce the identity order "abc"?
Answer
4, giving probability instead of .
Solution
Since 27 is not divisible by 6, the counts per permutation must be unequal; enumerating (Exercise 3) gives the counts 4, 5, 5, 5, 4, 4 for the six orders, with "abc" getting 4.
Exercise 2: Rising sequences after one riffle
Why does one riffle shuffle give at most 2 rising sequences?
Answer
Each packet keeps its internal order, and each packet is a run of consecutive values.
Solution
The top packet holds cards and the bottom , each in order after interleaving. So the values form at most two increasing runs by position.
Exercise 3: Exact bias (code)
Enumerate all choice sequences of the naive shuffle and count how often each permutation appears.
Answer
Counts 4, 5, 5, 5, 4, 4 (in sorted order of permutation).
Solution
from itertools import product
from collections import Counter
c = Counter()
for js in product(range(3), repeat=3):
a = list("abc")
for i, j in enumerate(js):
a[i], a[j] = a[j], a[i]
c["".join(a)] += 1
print(sorted(c.items()))[('abc', 4), ('acb', 5), ('bac', 5), ('bca', 5), ('cab', 4), ('cba', 4)]
Test yourself
In Fisher–Yates, position is swapped with a position chosen uniformly from…
- the whole list
- positions to
- positions to excluding
- the next position
Why can't the naive shuffle of 3 items be uniform?
- 27 is not divisible by 6
- It uses too few swaps
- The random generator is biased
- It is uniform