Sub topic 1
Counting Orderings: Permutations and n!
Prerequisites
This chapter assumes you know arrays and zero-based indexing, can write loops that swap two elements, understand basic probability (independent events, uniform distribution), and can read simple Python.
Permutations and n!
A permutation is one ordering of a set of items. A list of n distinct items has n! orderings. The first position has n choices, the next has n − 1, and so on down to 1. Three items have 3! = 6 orderings. A 52-card deck has 52! orderings, which is about 8 × 10^67.
What Makes a Shuffle Fair
A shuffle is fair (uniform) when every one of the n! permutations comes out with probability exactly 1/n!. Most orderings looking "mixed up" is not enough. Every ordering must be equally likely.
The Naive Shuffle and Where Its Bias Comes From
A common first attempt swaps each position with any random index:
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 itemsEach of the n steps picks from n indices, so there are n^n equally likely swap sequences. For n = 3 there are 27 sequences, and they must map onto 6 permutations. Because 27 is not divisible by 6, the sequences cannot split evenly. Some orderings must appear more often than others.
The Original Fisher-Yates Method
In 1938, Ronald Fisher and Frank Yates described a pencil-and-paper method:
- Write the numbers 1 to n.
- Pick a random number k between 1 and the count of numbers not yet struck out.
- Count to the k-th unstruck number, strike it out, and write it at the end of a new list.
- Repeat until every number is struck out.
The method is fair, but each step means scanning for the k-th unstruck number, so it takes O(n²) time.
The In-Place Fisher-Yates Shuffle
In 1964, Richard Durstenfeld adapted the method for computers. His version swaps the chosen item to the end of the array, which replaces striking out:
import random
def fisher_yates(items):
for i in range(len(items) - 1, 0, -1):
j = random.randint(0, i) # inclusive on both ends: 0 <= j <= i
items[i], items[j] = items[j], items[i]
return items
print(fisher_yates(list(range(10))))Position i picks from i + 1 choices, so the total number of swap sequences is n × (n − 1) × … × 2 = n!. That gives one sequence per permutation. The shuffle runs in O(n) time and uses O(1) extra space.
Exercise
For n = 4, how many swap sequences do the naive shuffle and Fisher-Yates each produce, and which one can be uniform?
Show answer
The naive shuffle produces 4^4 = 256 sequences and Fisher-Yates produces 4 × 3 × 2 = 24. There are 4! = 24 permutations, and 256 is not divisible by 24, so only Fisher-Yates can be uniform.