Sub topic 2
What Makes a Shuffle Fair
This chapter assumes you can read simple Python, know zero-based indexing, and are comfortable with basic probability: uniform distributions and independent events. It also uses the previous chapter's result that a list of n distinct items has n! orderings.
Before you can judge whether a shuffle algorithm is correct, you need a precise definition of "correct." Phrases like "it looks random" or "every card moves" are not testable, and several plausible definitions turn out to be too weak. This chapter fixes the definition the rest of the tutorial uses and shows why the weaker alternatives fail.
The definition
A shuffle is a procedure that takes a list and returns some reordering of it, using random choices along the way. Because the choices are random, a single run tells you almost nothing. The procedure is fully described only by its output distribution, which is the probability of each possible ordering coming out.
A shuffle of n distinct items is fair, or uniform, when every one of the n! permutations is produced with probability exactly 1/n!.
Three consequences follow directly:
- Fairness is a property of the distribution, not of any one output. The identity ordering
[1, 2, 3]is a perfectly legitimate result of a fair shuffle. It should simply appear 1 time in 6 on average. - Every permutation must be reachable. A procedure that can never produce some ordering is unfair, however random its other outputs look.
- No permutation may be favored, even slightly. A shuffle that gives one ordering probability 5/27 and another 4/27 is unfair, even though both are close to 1/6.
Why "close enough" is not the standard
You might ask why the definition demands exact equality. Fairness requirements usually come from settings where small biases add up or get exploited:
| Setting | What a biased shuffle causes |
|---|---|
| Card games and gambling | Players who know the bias can predict hands at better than chance |
| Randomized experiments (A/B tests) | Treatment groups differ in systematic ways, which skews results |
| Random sampling for surveys or audits | Some records are selected more often than their share |
| Randomized algorithms (quicksort pivots, load balancing) | Worst-case inputs become more likely than the analysis assumed |
| Music or playlist "shuffle" | Users notice repeated patterns |
An algorithm that is exactly uniform when given a perfect random source leaves only one possible cause of bias: the random source. That separation is what makes the problem manageable. You prove the algorithm correct once, then judge the random source as a separate question.
A tempting but wrong definition: every item lands everywhere equally
A common informal check is: "Does each item end up in each position with probability 1/n?" Call this position uniformity. Every fair shuffle has it. If all n! orderings are equally likely, then by symmetry item x sits at position p in exactly (n−1)! of them, and (n−1)!/n! = 1/n.
The converse fails. Consider the rotation shuffle: pick k uniformly from 0 to n−1 and rotate the list left by k places.
from fractions import Fraction
from itertools import permutations
from collections import Counter
def rotate(items, k):
return items[k:] + items[:k]
def rotation_distribution(items):
"""Exact output distribution of the rotation shuffle."""
n = len(items)
dist = Counter()
for k in range(n): # each k is chosen with probability 1/n
dist[tuple(rotate(items, k))] += Fraction(1, n)
return dist
def position_matrix(dist, items):
"""P(item x ends at position pos) for every x and pos."""
n = len(items)
matrix = {x: [Fraction(0)] * n for x in items}
for perm, p in dist.items():
for pos, x in enumerate(perm):
matrix[x][pos] += p
return matrix
items = [1, 2, 3]
dist = rotation_distribution(items)
print("Permutation probabilities:")
for perm in permutations(items):
print(" ", perm, dist.get(perm, Fraction(0)))
print("Position probabilities:")
for x, row in position_matrix(dist, items).items():
print(" item", x, [str(p) for p in row])Running it prints:
Permutation probabilities:
(1, 2, 3) 1/3
(1, 3, 2) 0
(2, 1, 3) 0
(2, 3, 1) 1/3
(3, 1, 2) 1/3
(3, 2, 1) 0
Position probabilities:
item 1 ['1/3', '1/3', '1/3']
item 2 ['1/3', '1/3', '1/3']
item 3 ['1/3', '1/3', '1/3']Every item is equally likely to be in every position, yet half the permutations never appear. Relative order is also fixed: 2 always comes right after 1, cyclically. For a deck of 52 cards the rotation shuffle reaches 52 orderings out of about 8 × 10^67.
Position uniformity is a single-item property. Fairness is a property of the whole ordering at once, so it also controls pairs, triples, and every other joint pattern. For n = 3, the rotation shuffle's distribution over permutations is lopsided, as the chart shows.
Other definitions that fall short
The rotation example generalizes. Each of the following properties is necessary for fairness but not sufficient:
- Every item moves. This is not even necessary. A fair shuffle leaves at least one item in place with probability about 63% for large n. Forcing every item to move produces a derangement distribution, which is a different and unfair one.
- Every permutation is possible. Reachability is necessary, but a shuffle can reach all n! orderings with unequal probabilities. The next chapter shows a short, popular algorithm that does exactly this.
- The output looks scrambled. Human judgment of randomness is poor. Fair shuffles often produce runs and clusters that look "not random" to people, and some music players deliberately give up uniformity to avoid them.
- Each run uses fresh randomness. Independence between runs is required, but it says nothing about the distribution within one run.
A useful way to check a candidate definition is to ask whether some obviously broken procedure satisfies it. If one does, the definition is too weak.
Edge cases of the definition
Empty and one-item lists. For n = 0 and n = 1 there is exactly one permutation (0! = 1! = 1), so any procedure that returns the list unchanged is fair. Correct implementations should handle these without special cases and without errors.
Two items. There are only two orderings. Any procedure that swaps with probability exactly 1/2 is fair. Small cases like this can hide bugs, because many broken algorithms are accidentally fair at n = 2 and fail from n = 3 onward. Test with n ≥ 3.
Duplicate values. The definition talks about permutations of positions. If the list is ['a', 'a', 'b'], it has 3! = 6 position permutations but only 3 distinct-looking arrangements. A fair shuffle still makes those 3 arrangements equally likely, because each arrangement corresponds to the same number of position permutations (2! = 2 here). In general, a uniform shuffle over positions induces a uniform distribution over distinct arrangements of a multiset. You do not need special handling for duplicates.
Fair relative to what. "Uniform" always means uniform given the algorithm's random choices. When you reason about an algorithm, you can compute its exact output distribution by listing every possible sequence of random choices with its probability, as rotation_distribution does. That exact calculation is the most reliable way to judge a small case, and the next chapter uses it.
Checking the definition in code
Here is a helper you can reuse. It takes an exact distribution, like the one computed above, and reports whether it is uniform:
from fractions import Fraction
from itertools import permutations
from math import factorial
def is_fair(dist, items):
"""True if every permutation of items has probability exactly 1/n!."""
target = Fraction(1, factorial(len(items)))
return all(dist.get(p, Fraction(0)) == target
for p in permutations(items))
def swap_coin_distribution(items):
"""For two items: swap with probability 1/2."""
a, b = items
return {(a, b): Fraction(1, 2), (b, a): Fraction(1, 2)}
print(is_fair(swap_coin_distribution([1, 2]), [1, 2])) # True
def rotate(items, k):
return items[k:] + items[:k]
rot = {}
for k in range(3):
key = tuple(rotate([1, 2, 3], k))
rot[key] = rot.get(key, Fraction(0)) + Fraction(1, 3)
print(is_fair(rot, [1, 2, 3])) # FalseThe helper uses Fraction instead of floats so that "exactly 1/n!" is checked exactly. With floats, rounding error could make a fair distribution fail or hide a small bias. Enumerating n! permutations is only practical for small n, roughly n ≤ 8. For larger inputs you rely on a proof, which a later chapter gives for Fisher-Yates, plus statistical sampling.
Exercise
A shuffle for n = 3 picks one of the three "reflections" (reversing the list, swapping positions 0 and 1, or swapping positions 1 and 2) with probability 1/3 each. Is it position-uniform? Is it fair?
Show answer
List the outputs for [1, 2, 3]: (3, 2, 1), (2, 1, 3), (1, 3, 2). Position 0 holds 3, 2, 1 once each, position 1 holds 2, 1, 3 once each, and position 2 holds 1, 3, 2 once each, so every item lands in every position with probability 1/3 and the shuffle is position-uniform. It is not fair, because only 3 of the 6 permutations occur, each with probability 1/3 instead of 1/6.
Exercise
A list contains ['x', 'x', 'y', 'y']. Under a fair shuffle, what is the probability that the result is ['x', 'y', 'x', 'y']?
Show answer
There are 4!/(2!·2!) = 6 distinct arrangements, and a fair shuffle makes them equally likely, so the probability is 1/6. Counted by positions: 2!·2! = 4 of the 24 position permutations give this arrangement, and 4/24 = 1/6.
Exercise
What is the smallest number of distinct permutations a shuffle of n items can output and still be position-uniform? Why does this show position uniformity is far weaker than fairness?
Show answer
n. Each permutation puts each item in only one position, so item x needs at least n outputs to reach all n positions. The n rotations meet that bound when each is chosen with probability 1/n. A fair shuffle needs all n! permutations. For n = 52 the gap is between 52 orderings and about 8 × 10^67.