Sub topic 3
The Naive Shuffle and Where Its Bias Comes From
This chapter assumes you can read short Python loops, swap two list elements, and count outcomes of independent random choices. It also builds on the previous chapter's definition: a fair shuffle of n items gives each of the n! orderings probability exactly 1/n!.
Most people who write a shuffle from scratch produce some version of the same algorithm. It looks reasonable and runs fast, and a casual glance at its output finds nothing wrong. It is still biased. This chapter shows where that bias comes from, using a counting argument you can check by hand.
The Shuffle Everyone Writes First
The usual first attempt walks through the list and swaps each position with a randomly chosen position anywhere in the list:
import random
def naive_shuffle(items):
n = len(items)
for i in range(n):
j = random.randint(0, n - 1) # any index: this is the bug
items[i], items[j] = items[j], items[i]
return items
print(naive_shuffle(list(range(10))))The reasoning behind it sounds fine. Every element gets moved, every destination is possible, and every random choice is uniform. The flaw is that uniform steps do not add up to a uniform result. To see why, look at what the loop actually draws.
Counting the Paths
Each run of naive_shuffle is fully determined by its sequence of random draws (j0, j1, ..., j(n-1)). Each draw is independent and has n equally likely values, so:
- There are n × n × ... × n = nⁿ distinct draw sequences ("paths").
- Every path has the same probability, 1/nⁿ.
- Each path ends in exactly one permutation.
A permutation's probability is therefore (number of paths that reach it) / nⁿ. For the shuffle to be fair, every one of the n! permutations needs the same number of paths, which is nⁿ / n!. That number has to be a whole number, because you can't have a fraction of a path.
| n | Paths (nⁿ) | Permutations (n!) | nⁿ / n! | Can be fair? |
|---|---|---|---|---|
| 2 | 4 | 2 | 2 | Yes, if paths split evenly |
| 3 | 27 | 6 | 4.5 | No |
| 4 | 256 | 24 | 10.67 | No |
| 5 | 3125 | 120 | 26.04 | No |
| 10 | 10,000,000,000 | 3,628,800 | 2755.73 | No |
Why n! Never Divides nⁿ for n ≥ 3
The table is not a coincidence for small n. Here is the general argument:
- n − 1 is a factor of n! = n × (n − 1) × ... × 1.
- n − 1 and n share no common factor other than 1, since any number dividing both would also divide their difference, which is 1.
- So n − 1 shares no prime factor with nⁿ, whose prime factors are exactly those of n.
- If n − 1 > 1, then n − 1 cannot divide nⁿ. Because n! is a multiple of n − 1, n! cannot divide nⁿ either.
For every n ≥ 3, the paths cannot be split evenly. The naive shuffle is biased for every list longer than two elements, and no particular random number generator or choice of seed can fix it. The algorithm itself is the problem.
The Exact Distribution for Three Items
For n = 3 there are only 27 paths, so you can list all of them. The following program does that, with no randomness involved. It also handles n = 4.
from itertools import product
from collections import Counter
def naive_outcomes(n):
"""Run the naive shuffle on every possible draw sequence and count results."""
counts = Counter()
for choices in product(range(n), repeat=n):
items = list(range(1, n + 1))
for i, j in enumerate(choices):
items[i], items[j] = items[j], items[i]
counts[tuple(items)] += 1
return counts
counts3 = naive_outcomes(3)
for perm, count in sorted(counts3.items()):
print(perm, count, f"{count / 27:.4f}")
counts4 = naive_outcomes(4)
print("n=4:", len(counts4), "permutations,",
"fewest paths:", min(counts4.values()),
"most paths:", max(counts4.values()))For n = 3 the output is:
| Permutation | Paths | Probability | Fair value |
|---|---|---|---|
| (1, 2, 3) | 4 | 0.1481 | 0.1667 |
| (1, 3, 2) | 5 | 0.1852 | 0.1667 |
| (2, 1, 3) | 5 | 0.1852 | 0.1667 |
| (2, 3, 1) | 5 | 0.1852 | 0.1667 |
| (3, 1, 2) | 4 | 0.1481 | 0.1667 |
| (3, 2, 1) | 4 | 0.1481 | 0.1667 |
Three orderings each come up 25% more often than the other three (5 paths against 4). A card game or a randomized experiment built on this shuffle would be measurably skewed. For n = 4 the program shows that all 24 permutations are reachable but with unequal path counts. As n grows, the spread between the most and least likely permutations keeps widening. Run the program to see the n = 4 numbers for yourself.
Why the Bias Is Easy to Miss
Every permutation is reachable, every element moves, and a printed shuffle of ten items looks random. The bias only appears when you count frequencies over many runs. Even then, with a long list the n! possible outcomes far outnumber any practical sample, so you have to test something smaller. Small inputs or position-by-position statistics work. A later chapter on testing builds that kind of check.
Where the Extra Paths Come From
The counting argument shows that bias must exist. The mechanism shows where it comes from: the naive loop lets an element that has already been placed get swapped out again. At step i, position j can be any index, including earlier positions the loop has already visited. Some final orderings can be reached through several different "undo and redo" routes, while others have fewer.
A fair algorithm needs exactly n! equally likely paths, one per permutation. You get that count if step i chooses among a shrinking number of options: n choices, then n − 1, then n − 2, down to 1. The product is n × (n − 1) × ... × 1 = n!. That is the structure of the Fisher-Yates shuffle covered in the next chapters. Restricting j to the part of the list not yet finalized turns nⁿ paths into n!.
Other Shortcuts with the Same Problem
The swap-with-any-index loop is the most common mistake, but similar shortcuts fail for related reasons.
| Approach | Fair? | Why |
|---|---|---|
| Swap position i with any index, for each i | No | nⁿ paths cannot split evenly over n! |
| Sort with a random comparator, such as `arr.sort(() => Math.random() - 0.5)` in JavaScript | No | The comparator is inconsistent. The result depends on which comparisons the sort algorithm makes, and some engines' sorts are strongly skewed |
| Pick n random swaps of any two positions | No | (n²)ⁿ paths, and the same divisibility problem |
| Sort by an independent random key per element | Yes, if keys never tie | Equivalent to ranking i.i.d. values. It costs O(n log n), and ties between keys add a small bias |
The random-comparator trick deserves a specific warning. A sort algorithm assumes its comparator is consistent: if a < b and b < c, then a < c. A coin-flip comparator breaks that assumption, so the output distribution depends on the sorting algorithm's internals. It can change between language versions and runtimes.
Summary
- A shuffle driven by independent uniform draws has as many equally likely paths as the product of its draw-range sizes.
- The naive shuffle has nⁿ paths. For every n ≥ 3, n! does not divide nⁿ, so the naive shuffle cannot be uniform.
- For three items, half the orderings get 5 of the 27 paths and the other half get 4.
- A fair design needs range sizes whose product is n!, which is what Fisher-Yates provides.
Exercise
A colleague's shuffle runs for i in range(n): j = random.randint(0, n - 1) but stops after n - 1 iterations instead of n. Use a counting argument to decide whether this can be fair for n = 4.
Show answer
It makes n - 1 = 3 draws with 4 choices each, so it has 4³ = 64 equally likely paths. A fair shuffle would need 64 / 24 paths per permutation, which is not a whole number (about 2.67). So it is biased for n = 4.
Exercise
Explain why the naive shuffle is fair for n = 2. Then use the factor n - 1 to explain why that argument breaks at n = 3.
Show answer
For n = 2 there are 2² = 4 paths and 2! = 2 permutations, and the paths split 2 and 2 (draws (0,1) and (1,0) leave [1,2], draws (0,0) and (1,1) give [2,1]). For n = 3, n! contains the factor n - 1 = 2. Since 2 shares no factor with 3, 2 does not divide 3³ = 27, so 6 cannot divide 27 either.
Exercise
A shuffle draws j from range(i, n) at step i, for i = 0 to n - 1. Multiply the range sizes and say whether the counting argument rules it out.
Show answer
The range sizes are n, n - 1, ..., 1, and their product is n!. The counting argument does not rule it out. Each permutation could get exactly one path, which is the condition for a fair shuffle. This is the forward form of Fisher-Yates. Proving that each path really gives a different permutation takes the argument in the correctness chapter.