Sub topic 1
Counting Orderings: Permutations and n!
Before you can judge whether a shuffle is fair, you need to know what it is choosing from. A shuffle takes a list and returns one of its possible orderings. This chapter counts those orderings, shows how fast the count grows, and explains why that number becomes the target every correct shuffle must hit.
Prerequisites
This chapter assumes you are comfortable with:
- Arrays and zero-based indexing (the first element is at index 0).
- Loops, and swapping two array elements.
- Basic probability: independent events, and what a uniform distribution is.
- Reading simple Python code, including
importstatements and f-strings.
You do not need any combinatorics. The counting rule used here is built up from scratch.
What a Permutation Is
A permutation of a list is one particular arrangement of all its elements, with each element used exactly once. For the list ["A", "B", "C"], the arrangement ["C", "A", "B"] is a permutation, and so is the original order ["A", "B", "C"].
A precise way to think about it is as a mapping from positions to elements. Position 0 gets one element, position 1 gets another, and so on. No element appears twice and none is left out. Mathematicians call this a bijection: every position pairs with exactly one element, and every element with exactly one position.
Two consequences matter for shuffling:
- The order of positions matters.
ABCandBACare different permutations, even though they contain the same letters. - A permutation rearranges elements. It never adds, removes, or copies them. A shuffle that ever outputs
["A", "A", "C"]is broken. Being unfair would be a separate problem.
The Counting Rule
To count permutations, fill the positions one at a time and count your choices at each step.
- Position 0 can hold any of the n elements: n choices.
- Position 1 can hold any element not already used: n − 1 choices.
- Position 2 has n − 2 choices, and so on.
- The last position has exactly 1 choice: whatever is left.
Each choice at one step can pair with every choice at the next step, so the counts multiply. The total is
n × (n − 1) × (n − 2) × … × 2 × 1
This product is called n factorial and written n!. For three elements, 3! = 3 × 2 × 1 = 6.
The diagram below draws the decision process for [A, B, C] as a tree. Each level fills one position, and each path from top to bottom spells out one permutation.
This step-by-step "pick one of the remaining elements" structure is more than a counting trick. The Fisher-Yates shuffle, later in this tutorial, is built from exactly this tree. It walks down one random path, choosing uniformly among the remaining elements at each level.
Edge Cases: 0! and 1!
A list with one element has exactly one ordering, so 1! = 1. An empty list also has exactly one ordering, the empty arrangement, so 0! = 1 by definition. That fits the code too: shuffling an empty list or a one-element list should do nothing, and a correct shuffle loop over such a list runs zero swaps.
Checking the Count in Code
Python's standard library can list every permutation, which lets you confirm the counting rule directly.
import math
from itertools import permutations
items = ["A", "B", "C"]
perms = list(permutations(items))
for p in perms:
print("".join(p))
print("listed:", len(perms))
print("3! =", math.factorial(len(items)))Output:
ABC
ACB
BAC
BCA
CAB
CBA
listed: 6
3! = 6itertools.permutations returns the permutations in lexicographic order of input positions, which matches the leaves of the tree above from left to right. Listing every permutation only works for small n. The next section shows why.
How Fast n! Grows
Factorials grow faster than any exponential with a fixed base. The script below prints n! and its size in bits, log2(n!). The bit count is the number of random bits you would need, at minimum, to pick one permutation out of all of them.
import math
print(f"{'n':>3} {'n!':>12} {'log2(n!)':>9}")
for n in [1, 2, 3, 4, 5, 8, 10, 13, 20, 52]:
f = math.factorial(n)
print(f"{n:>3} {f:>12.3e} {math.log2(f):>9.2f}")The results, rounded:
| n | n! | log2(n!) bits |
|---|---|---|
| 1 | 1 | 0.00 |
| 2 | 2 | 1.00 |
| 3 | 6 | 2.58 |
| 4 | 24 | 4.58 |
| 5 | 120 | 6.91 |
| 8 | 40,320 | 15.30 |
| 10 | 3,628,800 | 21.79 |
| 13 | 6,227,020,800 | 32.54 |
| 20 | about 2.43 × 10^18 | 61.08 |
| 52 | about 8.07 × 10^67 | 225.58 |
A standard 52-card deck has about 8 × 10^67 orderings. If every computer ever built had been shuffling decks since the Big Bang, it would have produced a vanishingly small fraction of them. So you can never test a shuffle by checking that every permutation of a real deck shows up. Empirical tests, covered later, use tiny lists where n! is small enough to count.
The bit column will come back in the chapter on random generators. A generator with only 32 or 64 bits of internal state cannot possibly reach all 52! orderings, because 52! needs more than 225 bits.
Common Errors When Counting Orderings
Confusing n! with n^n
If each of n positions could hold any of n elements independently, there would be n^n arrangements. For n = 3 that is 27. Most of those repeat elements, such as AAB, so they are not permutations. Only 6 of the 27 are valid orderings. Keep the two numbers apart. The next chapters show that a common buggy shuffle produces n^n equally likely swap sequences, and that mismatch with n! is the source of its bias.
Confusing Permutations with Combinations
A combination is a choice of which items to take, ignoring order. A permutation cares about order. Choosing 2 cards from {A, B, C} gives 3 combinations (AB, AC, BC) but 6 ordered arrangements (AB, BA, AC, CA, BC, CB). A shuffle produces a full ordering, so permutations are the right count. Ordered samples of k out of n items number n × (n − 1) × … × (n − k + 1). That count returns in the chapter on partial shuffles.
Forgetting That Positions, Not Values, Are Permuted
If a list contains duplicate values, such as [1, 1, 2], a shuffle still permutes the three positions, giving 3! = 6 position orderings. Several of those look identical when printed. There are only 3 distinct value sequences: 112, 121, and 211. In general, a list with groups of repeated values of sizes k1, k2, … has n! / (k1! × k2! × …) distinct value sequences. A fair shuffle gives each of the 6 position orderings probability 1/6, so each visible sequence here appears with probability 2/6. When you test a shuffle by counting outcomes, use distinct values, or your expected frequencies will be wrong.
Why This Number Is the Target
Every shuffle of an n-element list outputs one of the n! permutations. The rest of this tutorial depends on that fact:
- A fair shuffle must give each permutation probability exactly 1/n!. The next chapter makes this definition precise.
- Any procedure whose random choices split into a number of equally likely outcomes that n! does not divide evenly cannot be fair. This is the counting argument used against the naive shuffle.
- The source of randomness must be able to tell apart at least n! different outcomes, which is about log2(n!) bits.
Exercises
Exercise
How many permutations does the list [10, 20, 30, 40] have? Write out every permutation whose first element is 30.
Show answer
4! = 24 permutations. Those starting with 30 are the 3! = 6 orderings of the remaining elements: [30, 10, 20, 40], [30, 10, 40, 20], [30, 20, 10, 40], [30, 20, 40, 10], [30, 40, 10, 20], [30, 40, 20, 10].
Exercise
A procedure for shuffling 4 items makes 4 independent random choices, each uniform over 4 options, and maps every sequence of choices to a permutation. Using only counting, can this procedure be fair?
Show answer
No. It has 4^4 = 256 equally likely choice sequences, and a fair shuffle needs each of the 4! = 24 permutations to get the same share. 256 / 24 is not a whole number (24 does not divide 256, since 24 has a factor of 3 and 256 = 2^8), so the permutations cannot all receive the same number of sequences.
Exercise
A game shuffles a deck of 30 distinct cards using a random generator with 64 bits of internal state. Without running code, use log2(n!) to decide whether every ordering of the deck can be produced. (Hint: log2(20!) is about 61, and each extra card adds log2 of its position count.)
Show answer
It cannot. log2(30!) is about 107.7 bits, well above 64. A 64-bit generator has at most 2^64 starting states, so the shuffle can produce at most 2^64 distinct orderings, a tiny fraction of the roughly 2.65 × 10^32 orderings of 30 cards.