Sub topic 8
Off-by-One Errors That Break Fairness
This chapter assumes you already know the in-place Fisher-Yates loop and the proof that it is uniform. It also assumes you can read Python's random.randint(a, b), which includes both ends, and random.randrange(a, b), which excludes b.
Fisher-Yates is correct only when its index ranges are exactly right. If a bound is off by one, the code still runs and still returns a scrambled-looking list. Nothing crashes, and a quick glance at the output shows nothing wrong. The only damage is that some orderings become more likely than others, or can never appear at all.
The counting check
The uniformity proof rests on one count. At step i, the swap index j must have exactly i + 1 possible values. Each sequence of choices must also lead to a different permutation. Multiplying the choices gives n × (n−1) × … × 2 = n!, which is one sequence for each permutation.
You can use this as a quick audit for any shuffle loop. Multiply the number of choices at each step. If the product is not n!, the shuffle cannot be uniform. If the product is n! but the bounds differ from the standard loop, you still need to check that every permutation can be reached.
| Variant | Code for `j` (loop `i` from n−1 down to 1) | Total outcomes | Effect |
|---|---|---|---|
| Correct | `randint(0, i)` | n! | Uniform |
| Excludes `i` | `randrange(i)` or `randint(0, i - 1)` | (n−1)! | Only single-cycle permutations (Sattolo's algorithm) |
| Any index | `randint(0, n - 1)` | nⁿ⁻¹ | Biased, as in the naive shuffle |
| Loop starts at n−2 | `randint(0, i)` | (n−1)! | The last element never moves |
| Loop runs down to 0 | `randint(0, i)` | n! | Harmless: the extra step swaps item 0 with itself |
Seeing the damage exactly
You don't need random trials to see these effects. The script below lists every possible sequence of choices for n = 3 and counts the permutation each sequence produces:
from collections import Counter
from itertools import product
def enumerate_outcomes(n, choices_for):
steps = list(range(n - 1, 0, -1))
counts = Counter()
for picks in product(*(choices_for(i, n) for i in steps)):
items = list(range(n))
for i, j in zip(steps, picks):
items[i], items[j] = items[j], items[i]
counts[tuple(items)] += 1
return counts
rules = {
"correct": lambda i, n: range(0, i + 1),
"excludes i": lambda i, n: range(0, i),
"any index": lambda i, n: range(0, n),
}
for name, rule in rules.items():
print(name, dict(sorted(enumerate_outcomes(3, rule).items())))Each rule produces a different result:
- Correct: each of the 6 permutations appears exactly once.
- Excludes
i: only(1, 2, 0)and(2, 0, 1)appear. These are the two 3-cycles. - Any index: the 9 choice sequences are spread across 6 permutations. Since 9 is not a multiple of 6, some permutations must appear more often than others.
The forward version has the same trap
Fisher-Yates can also run from the front of the list. In that form, step i must pick j from i to n − 1, including both ends. The correct call is randint(i, n - 1). Writing randint(i + 1, n - 1) reproduces Sattolo's single-cycle behavior from the other direction.
In both directions, the rule is the same: the current position must be allowed to swap with itself.
Exercise
A colleague writes for i in range(len(a) - 1, 0, -1): j = random.randint(0, i - 1) and says it "shuffles fine" because the output always looks scrambled. Use the counting check to explain the problem for n = 4, and give the fix.
Show answer
Step i offers only i choices, so there are 3 × 2 × 1 = 6 outcomes. A fair shuffle needs one outcome for each of the 4! = 24 permutations. This loop is Sattolo's algorithm: it produces only the 6 single-cycle permutations, and no element ever stays in its original position. The fix is j = random.randint(0, i).
Exercise
Is changing the loop to range(len(a) - 1, -1, -1) (so it runs down to i = 0) a fairness bug?
Show answer
No. At i = 0, the only possible choice is j = 0, so the step swaps item 0 with itself. The total is still n! outcomes, and the step costs one extra random call.