Sub topic 4
The Original Fisher-Yates Method
This chapter assumes you know what a permutation is, that a fair shuffle gives each of the n! orderings probability 1/n!, and why the naive "swap with any index" shuffle fails. You should also be comfortable reading short Python functions and converting between 1-based and 0-based positions.
The shuffle that programmers use today began as a set of instructions for people working with pencil and paper. Ronald Fisher and Frank Yates published it in 1938 in their book Statistical Tables for Biological, Agricultural and Medical Research. Their readers were experimenters who needed to randomize, for example, which plot of land got which treatment. Computers were not available, so the procedure had to be something a person could carry out with a printed table of random digits. If you understand that version, the in-place algorithm in the next chapter will look like an optimization of something you already know.
The Procedure on Paper
The method uses a scratch list and a result list. It goes like this:
- Write the numbers 1 to N in a row. This is the scratch list.
- Count how many numbers in the scratch list are not yet struck out. Call that count m.
- Pick a random number k between 1 and m, with each value equally likely.
- Counting from the left and skipping struck numbers, find the k-th number that has not been struck out. Strike it out and write it at the end of the result list.
- Repeat from step 2 until every number is struck out.
The result list is the shuffled order. The scratch list is only there to keep track of what is left.
The key point is in step 3. The range of k shrinks by one each round: N choices, then N − 1, then N − 2, and so on down to 1. That gives exactly N × (N − 1) × … × 1 = N! possible sequences of choices. Every sequence of choices produces a different result list, and every ordering can be reached by exactly one sequence. The naive shuffle has nⁿ equally likely sequences, and that number does not divide evenly among n! orderings. Here the sequences match the orderings one to one. A later chapter turns this into a full proof.
A Worked Example with N = 8
Suppose the random picks come out as 3, 4, 6, 1, 3, 2, 2, 1. Each pick must lie between 1 and the current m, and each of these does.
| Step | m (unstruck) | k | Unstruck numbers before the pick | Struck this step | Result so far |
|---|---|---|---|---|---|
| 1 | 8 | 3 | 1 2 3 4 5 6 7 8 | 3 | 3 |
| 2 | 7 | 4 | 1 2 4 5 6 7 8 | 5 | 3 5 |
| 3 | 6 | 6 | 1 2 4 6 7 8 | 8 | 3 5 8 |
| 4 | 5 | 1 | 1 2 4 6 7 | 1 | 3 5 8 1 |
| 5 | 4 | 3 | 2 4 6 7 | 6 | 3 5 8 1 6 |
| 6 | 3 | 2 | 2 4 7 | 4 | 3 5 8 1 6 4 |
| 7 | 2 | 2 | 2 7 | 7 | 3 5 8 1 6 4 7 |
| 8 | 1 | 1 | 2 | 2 | 3 5 8 1 6 4 7 2 |
The final pick is forced, because only one number is left and k can only be 1. Even so, N! counts it as a factor of 1. In practice you can stop after N − 1 picks.
Notice that k is a rank among the survivors. It is not a position in the original row. In step 2, k = 4 selects 5 because 3 has already been struck and is skipped. Mixing up these two meanings is the most common mistake people make when they reproduce the method.
Getting Random Numbers from a Table
Fisher and Yates' readers did not have a randint function. They read digits from a printed table of random numbers. Getting a uniform value from 1 to m out of decimal digits takes some care. For m = 6 you can read single digits and ignore 0, 7, 8, and 9. For m = 7 with two-digit numbers from 00 to 99, you would keep only the values that fall inside the largest multiple of 7 and discard the rest. Taking every value and reducing it with a remainder gives some outcomes a slightly larger share. This is the same modulo bias that computer implementations face, and a later chapter covers it with rejection sampling. People had to deal with the problem by hand decades before programmers met it.
Translating the Method into Code
A literal translation keeps the original row and marks entries as struck. This version takes the picks as an argument, so you can reproduce the worked example exactly:
def strike_out_shuffle(items, picks):
"""Original Fisher-Yates with explicit picks (1-based ranks among survivors)."""
n = len(items)
struck = [False] * n
result = []
for m, k in zip(range(n, 0, -1), picks):
if not 1 <= k <= m:
raise ValueError(f"pick {k} out of range 1..{m}")
count = 0
for idx in range(n):
if not struck[idx]:
count += 1
if count == k:
struck[idx] = True
result.append(items[idx])
break
return result
print(strike_out_shuffle(list(range(1, 9)), [3, 4, 6, 1, 3, 2, 2, 1]))
# [3, 5, 8, 1, 6, 4, 7, 2]To shuffle randomly, generate each pick as you go. A Python list can stand in for the scratch row, because removing an element closes the gap. That handles the "skip struck numbers" step for you:
import random
def original_fisher_yates(items):
remaining = list(items) # the scratch row; the input is not modified
result = []
while remaining:
k = random.randint(1, len(remaining)) # 1 <= k <= m, as on paper
result.append(remaining.pop(k - 1)) # convert the 1-based rank to a 0-based index
return result
print(original_fisher_yates(range(1, 11)))Both functions produce correctly distributed shuffles, provided the random source itself is uniform. Where they fall short is efficiency.
Why It Is Slow on a Computer
On paper, finding the k-th unstruck number means scanning across the row. The flag-based code does the same work: each step may scan up to n entries. The pop version hides the scan without removing it. Removing an element from the middle of a Python list shifts every element after it. Either way, step i costs time proportional to the number of items left. The total is about n + (n − 1) + … + 1 ≈ n²/2 operations, so the method is O(n²). The result list also uses O(n) extra memory.
A person shuffling 20 plots of land never notices this. A program shuffling ten million records does. In 1964 Richard Durstenfeld published an in-place version (Algorithm 235 in Communications of the ACM), and Donald Knuth later popularized it in The Art of Computer Programming. Durstenfeld's version keeps the same sequence of choices and replaces the scan with a single swap. The next chapter builds it.
Mistakes When Reproducing the Original
| Mistake | What happens | Fair? |
|---|---|---|
| Picking k from 1..N every round instead of 1..m | k can point past the survivors. The code crashes or wraps around. | Broken |
| Counting struck numbers when finding the k-th entry | The pick can land on a number that is already used | Broken |
| Re-rolling whenever the pick hits a struck number in the original row | Each draw is uniform among the survivors, but the number of rolls grows to about n·ln n | Fair but slow |
| Using `pop(k)` with a 1-based k | Rank m is out of range, and rank 1 can never be chosen | Broken |
| Reducing random-table digits with a remainder | Small values become a little more likely | Biased |
The re-roll row is worth a closer look. If you pick a position uniformly from the whole original row and reject struck ones, every surviving position is still equally likely, so fairness holds. You pay for it in wasted draws. Near the end almost every roll misses, which is the coupon-collector problem. Fairness depends on whether each surviving item has the same chance at every step. It does not depend on how many draws you throw away to get there.
Exercise
Using strikeoutshuffle on the numbers 1 to 5, which picks produce the result [5, 4, 3, 2, 1]? Which picks produce [1, 2, 3, 4, 5]?
Show answer
To get the reversed order you always take the last survivor, so the picks are [5, 4, 3, 2, 1]. To keep the original order you always take the first survivor, so the picks are [1, 1, 1, 1, 1]. Each ordering has exactly one pick sequence, which matches the one-to-one correspondence between the 5! = 120 sequences and the 120 orderings.
Exercise
A colleague writes k = random.randint(1, len(items)) (the original length) inside the while loop of originalfisheryates, and wraps the index with remaining.pop((k - 1) % len(remaining)). The code no longer crashes. Is the shuffle fair? Check the second step for n = 3.
Show answer
It is not fair. In step 2 there are two survivors, but k is drawn from 1..3. The values k - 1 = 0, 1, 2 reduce mod 2 to 0, 1, 0, so the first survivor is chosen with probability 2/3 instead of 1/2. This is modulo bias applied to the rank.
Exercise
Roughly how many element comparisons or shifts does the original method need to shuffle 1,000,000 items, and how does this compare with an algorithm that does one constant-time swap per item?
Show answer
About n²/2 = 5 × 10¹¹ basic operations, compared with about 10⁶ for a one-swap-per-item method. That is roughly 500,000 times more work.