Sub topic 8
Off-by-One Errors That Break Fairness
This chapter assumes you already know the in-place Fisher-Yates loop from earlier chapters, the counting proof that it gives each of the n! permutations probability 1/n!, and the counting argument against the naive shuffle. You should also be able to read Python's range and random calls.
The Fisher-Yates shuffle is only three lines long, and two of those lines contain an index bound. Getting either bound wrong by one gives you code that still runs and still produces output that looks shuffled. The output is no longer uniform, though. Some of these mistakes skip some permutations entirely. Others make certain permutations more likely than others. None of them raises an error, so you have to know what to look for.
The two bounds that must be right
Here is the correct loop again, with both bounds labelled:
import random
def fisher_yates(items):
for i in range(len(items) - 1, 0, -1): # bound 1: i runs n-1 down to 1
j = random.randint(0, i) # bound 2: 0 <= j <= i, inclusive
items[i], items[j] = items[j], items[i]
return itemsThe proof of uniformity depends on two facts:
- Step i has exactly i + 1 equally likely choices, so the number of choice sequences is n × (n − 1) × … × 2 = n!.
- Each choice sequence leads to a different permutation, so the n! sequences match the n! permutations one to one.
Any off-by-one change breaks one of these facts. Either the number of choice sequences stops being n!, or two sequences start producing the same permutation. To check any variant, ask two questions. How many equally likely choice sequences does it have? Does it reach every permutation the same number of times?
Mistake 1: excluding i from the choice (you get Sattolo's algorithm)
This is the most common mistake, and it is easy to miss in review:
j = random.randrange(i) # 0 <= j < i -- WRONG for a general shuffleIt also appears in JavaScript as Math.floor(Math.random() * i) instead of * (i + 1).
Leaving out i means the element at position i can never stay where it is during its own step. The number of choice sequences drops to (n − 1) × (n − 2) × … × 1 = (n − 1)!. That is n times fewer than n!. The code is now Sattolo's algorithm. It produces only permutations that form a single cycle, and each of those has probability 1/(n − 1)!.
The visible effect is that no element ever ends up in its original position. In the final ordering, item k is never at index k. For n = 3, the code can only produce 2 of the 6 orderings. A card game built on this code would never leave a card in its starting slot. A player who noticed that would gain an advantage.
Mistake 2: choosing from the whole array (you get the naive shuffle)
j = random.randint(0, len(items) - 1) # any index -- WRONGIf the upper bound stays at n − 1 when it should shrink with i, the code is the naive shuffle from the earlier chapter. With a loop over all n positions it has nⁿ choice sequences. For n ≥ 3, n! does not divide nⁿ evenly, so the permutations cannot all be equally likely. All permutations are still reachable. The problem is that they come up with different frequencies, which makes this bias harder to notice than Mistake 1.
Mistake 3: the loop stops one step early
for i in range(len(items) - 1, 1, -1): # stops at i = 2 -- WRONG
j = random.randint(0, i)
items[i], items[j] = items[j], items[i]Python's range excludes its stop value. Someone who knows the last useful step is i = 1 might write 1 as the stop, and then the i = 1 step never runs. That step is the one that decides the order of positions 0 and 1. Without it there are n!/2 choice sequences, each of which still leads to a different permutation. The result is that exactly half the permutations can never occur. The other half each have probability 2/n!.
Mistake 4: the loop runs one step too long (harmless)
for i in range(len(items) - 1, -1, -1): # includes i = 0
j = random.randint(0, i) # always 0 when i = 0At i = 0 the only possible choice is j = 0, and swapping position 0 with itself does nothing. This version is still uniform and only wastes one iteration. It is worth recognizing so that you don't "fix" it into Mistake 3.
The same mistakes in the forward loop
Some code walks the array from the front:
import random
def fisher_yates_forward(items):
n = len(items)
for i in range(n - 1):
j = random.randint(i, n - 1) # i <= j <= n-1, inclusive
items[i], items[j] = items[j], items[i]
return itemsThe rule is the same mirrored: position i must be allowed to keep its own element. Writing random.randint(i + 1, n - 1) is the forward version of Mistake 1 and also gives Sattolo's algorithm. Writing random.randint(0, n - 1) is the naive shuffle again.
Seeing every outcome exactly
Sampling only estimates a distribution. For small n you can do better and list every choice sequence. The program below replaces the random calls with an enumeration of all allowed values of j, runs each sequence, and counts the permutations it produces.
from collections import Counter
from itertools import permutations, product
def exhaustive(n, steps):
"""steps: list of (i, lo, hi); j takes every value in lo..hi inclusive."""
counts = Counter()
ranges = [range(lo, hi + 1) for _, lo, hi in steps]
for js in product(*ranges):
items = list(range(n))
for (i, _, _), j in zip(steps, js):
items[i], items[j] = items[j], items[i]
counts[tuple(items)] += 1
return counts
n = 3
variants = {
"correct": [(i, 0, i) for i in range(n - 1, 0, -1)],
"j < i": [(i, 0, i - 1) for i in range(n - 1, 0, -1)],
"any j": [(i, 0, n - 1) for i in range(n)],
"skips i = 1": [(i, 0, i) for i in range(n - 1, 1, -1)],
"extra i = 0": [(i, 0, i) for i in range(n - 1, -1, -1)],
}
print("perms:", list(permutations(range(n))))
for name, steps in variants.items():
counts = exhaustive(n, steps)
row = [counts.get(p, 0) for p in permutations(range(n))]
print(f"{name:12} total={sum(row):2} {row}")The output, with permutations in lexicographic order, is:
| Variant | Sequences | (0,1,2) | (0,2,1) | (1,0,2) | (1,2,0) | (2,0,1) | (2,1,0) | Verdict |
|---|---|---|---|---|---|---|---|---|
| correct | 6 | 1 | 1 | 1 | 1 | 1 | 1 | uniform |
| j < i | 2 | 0 | 0 | 0 | 1 | 1 | 0 | cycles only |
| any j | 27 | 4 | 5 | 5 | 5 | 4 | 4 | biased |
| skips i = 1 | 3 | 1 | 1 | 0 | 0 | 0 | 1 | half missing |
| extra i = 0 | 6 | 1 | 1 | 1 | 1 | 1 | 1 | uniform |
An exhaustive check like this, run for n = 3 and n = 4, works well as a unit test. It is deterministic, it finishes in milliseconds, and it catches every mistake in this chapter.
Inclusive or exclusive: know your API
Most real-world off-by-one shuffle bugs come from mixing APIs that treat the upper bound differently. Python's range and randrange exclude it, but randint includes it. Check the bound for whatever function you call:
| Language | Correct call for 0 ≤ j ≤ i | Upper bound in that call |
|---|---|---|
| Python | `random.randint(0, i)` or `random.randrange(i + 1)` | inclusive / exclusive |
| JavaScript | `Math.floor(Math.random() * (i + 1))` | exclusive |
| Java | `rnd.nextInt(i + 1)` | exclusive |
| C# | `rng.Next(i + 1)` | exclusive |
| Go | `rand.Intn(i + 1)` | exclusive |
| Rust (`rand`) | `rng.gen_range(0..=i)` | inclusive range syntax |
Exercise
A colleague writes j = Math.floor(Math.random() * i) inside a backward loop from i = arr.length - 1 down to 1. For an array of 4 elements, how many distinct orderings can it produce, and what property do they all share?
Show answer
It is Sattolo's algorithm. The number of choice sequences is 3 × 2 × 1 = 6 = (4 − 1)!, and each gives a different single 4-cycle, so it produces exactly 6 of the 24 orderings, each with probability 1/6. None of them leaves any element in its original position. The fix is Math.floor(Math.random() * (i + 1)).
Exercise
The loop for i in range(len(items) - 1, 1, -1) with j = random.randint(0, i) runs on a 4-element list. How many permutations are reachable, and with what probability each?
Show answer
The i = 1 step is skipped, so there are 4 × 3 = 12 choice sequences, each producing a different permutation. Twelve of the 24 permutations are reachable, each with probability 1/12. The other twelve never occur. Changing the stop value to 0 fixes it.
Exercise
Extend the exhaustive checker to n = 4 for the "any j" variant. How many choice sequences are there, and why can the result not be uniform?
Show answer
There are 4^4 = 256 sequences spread over 24 permutations. Since 256 / 24 is not a whole number, the permutations cannot all get the same count, so some must be more likely than others.