Why is a shuffle that swaps every slot with any random index biased, and how does Fisher-Yates make every ordering equally likely?
answer
- count the swap sequences
- n to the n versus n factorial
- shrinking range for the swap partner
- inclusive upper bound matters
- seed state limits reachable orders
basics
~20 sSwapping every slot with any of n indices gives n^n equally likely sequences, which cannot split evenly over n! orderings. Fisher-Yates swaps slot i only with an index in [0, i], giving exactly n! equally likely paths, one per ordering.
solid answer
~50 sFor a deck of three, the naive loop has `3^3 = 27` equally likely swap sequences but only `3! = 6` orderings; 27 does not divide by 6, so three orderings get 5 chances in 27 and three get 4. Fisher-Yates walks `i` from `n - 1` down to `1`, picks `j` uniformly in `[0, i]` inclusive and swaps `a[i]` with `a[j]`: `n * (n - 1) * ... * 2 = n!` paths, each producing a different ordering, in `O(n)` time and in place. The traps are picking `j` in `[0, i - 1]`, which turns it into Sattolo's algorithm and only produces single-cycle orderings, mapping random bits to `[0, i]` with a plain modulo, which slightly favours small values, and sorting with a random comparator, which is biased too. A generator seeded from 32 bits can also reach at most `2^32` of the `52!` deck orders.
code
pseudocode · 4 linesfunction shuffle(items, rng):
for i from length(items) - 1 down to 1:
j = rng.int_in_range(0, i) // uniform, both ends inclusive, no modulo bias
swap(items[i], items[j])go deeper
Recall the Fisher-Yates loop: walk down from the last slot and swap with a uniform index from zero up to and including the current slot.
Explain the counting argument: n to the n swap sequences cannot split evenly over n factorial orderings, while Fisher-Yates has exactly n factorial paths.
Catch the subtle defects in review: the exclusive upper bound that becomes Sattolo's algorithm, modulo bias in range mapping, random comparators, and a shuffle sharing a stream with cosmetics.
Ship one tested shuffle and one unbiased range routine for the whole codebase, with a distribution test in the build, so fairness bugs cannot be reintroduced per feature.
## What an unbiased shuffle means A **shuffle** is unbiased when every one of the `n!` orderings of `n` items is equally likely. A roguelike deck of 20 cards, a randomised order of rooms on a floor, or a bag of upcoming puzzle pieces all depend on it. A biased shuffle rarely looks broken in a playtest; it shows up as players noticing that the same card keeps opening the hand, or as a speedrun community finding a favoured ordering. ## Why the naive swap is biased The tempting loop is: for each slot `i` from `0` to `n - 1`, swap `a[i]` with `a[j]` where `j` is uniform over **all** `n` indices. It does `n` independent draws with `n` outcomes each, so there are `n^n` equally likely **swap sequences**. Each sequence produces one ordering, so an ordering's probability is the number of sequences that produce it divided by `n^n`. For that to equal `1 / n!` for every ordering, `n^n` must be divisible by `n!`. For `n = 3`, `27` is not divisible by `6`; in general `n - 1` shares no factor with `n`, so for any `n >= 3`, `n!` never divides `n^n`. Some orderings must be more likely than others. Counting all 27 sequences for the list `1, 2, 3`: | Ordering | Sequences | Probability | |---|---|---| | 1 2 3 | 4 | 4/27 | | 1 3 2 | 5 | 5/27 | | 2 1 3 | 5 | 5/27 | | 2 3 1 | 5 | 5/27 | | 3 1 2 | 4 | 4/27 | | 3 2 1 | 4 | 4/27 | A fair shuffle would give each `1/6`, about `4.5/27`. The skew never goes away for any `n >= 3`, and it is easy to measure with a tally. ## Fisher-Yates step by step The **Fisher-Yates** shuffle (in the in-place form often credited to Durstenfeld) builds the shuffled array from the back: 1. Let `i` run from `n - 1` down to `1`. 2. Pick `j` uniformly from `0` to `i` **inclusive**. 3. Swap `a[i]` and `a[j]`; slot `i` is now final and never touched again. At step `i` there are `i + 1` choices, so the total number of paths is `n * (n - 1) * ... * 2 = n!`. Every path produces a different ordering, because the item placed in each final slot is a distinct choice among the items not yet placed. With `n!` paths and `n!` orderings in a one-to-one match, each ordering has probability exactly `1 / n!`. The cost is `n - 1` random draws and swaps, `O(n)` time and no extra memory. An equivalent forward form lets `i` run up from `0` to `n - 2` with `j` in `[i, n - 1]`. Both are correct; mixing their bounds is where bugs come from. ## The traps that survive code review - **Excluding the slot itself.** Picking `j` in `[0, i - 1]` is **Sattolo's algorithm**. It produces only orderings that form one single cycle, so no item ever stays in its original slot and most orderings never appear. For the list `1, 2, 3` it yields only `2 3 1` and `3 1 2`. - **Modulo bias.** Mapping a 32-bit random value to `[0, i]` with `value mod (i + 1)` favours small results whenever `i + 1` does not divide `2^32`. Use rejection: discard values in the incomplete final block and draw again, or a multiply-and-shift mapping that also rejects the few biased values. - **Random comparators.** Sorting with a comparator that returns a random answer is biased, and some sort routines misbehave when a comparator is inconsistent. - **Seed space.** A shuffle can only be as varied as its generator's state. A generator seeded from a 32-bit value has at most `2^32` starting points, while a 52-card deck has `52!`, about `8.07 * 10^67` or roughly `2^225.6` orderings. Almost all deck orders are unreachable. For a game this rarely matters, but it does mean that the seed, not the shuffle, sets the true variety. - **One shared generator.** If the shuffle draws from the same stream as particle effects, a seeded replay shuffles differently when visual settings change. ## Testing a shuffle Run the shuffle many times on a small input and tally how often each item lands in each slot. With `n` items and `N` runs, each cell should sit near `N / n`; the naive swap on three items puts item 2 in the first slot 10 times in 27 but in the middle slot only 8 times in 27, while a fair shuffle gives 9 each. For a stronger check, tally whole orderings for `n = 3` or `4` and compare each count with `N / n!`. A shuffle test belongs in the build of any game whose fairness players will reverse-engineer.
- How do you map a 32-bit random value to an integer in [0, k) without bias?Plain `value mod k` over-represents small results when `k` does not divide `2^32`. Rejection fixes it: compute the largest multiple of `k` that fits, discard values at or above it and draw again. The multiply-and-shift variant multiplies the value by `k`, keeps the high 32 bits as the result and rejects only the few low-part values that would bias it, avoiding a division in the common case.
- How do you deal a random hand of 5 cards from 52 without shuffling the whole deck?Run only the first five steps of Fisher-Yates: for `i` from `51` down to `47`, swap `a[i]` with a uniform `a[j]`, `j` in `[0, i]`, and take slots 47 to 51. Each step fixes one uniformly chosen card, so the partial shuffle gives an unbiased hand in five draws.
- When is Sattolo's algorithm actually what you want?When the result must be a single cycle: for example, a secret-partner assignment where nobody draws themselves and following partner to partner visits everyone, or a linked tour through every room. It is exactly Fisher-Yates with `j` drawn from `[0, i - 1]`, so it is a deliberate choice, never a substitute for a fair shuffle.
- Swapping every slot with any random index is fair because each swap is uniform.
- Drawing the partner from 0 to i minus 1 just skips a wasted self-swap.
- Taking a random value modulo the range is always unbiased.
- Sorting with a comparator that returns a random result is a fine shuffle.
- A 32-bit seed can produce every possible ordering of a 52-card deck.