Sub topic 15
Sattolo's Algorithm and Cyclic Permutations
This chapter assumes you already know the in-place Fisher-Yates shuffle, the proof that it is uniform, and the off-by-one pitfalls covered earlier. You should also be able to read Python and follow a short induction argument.
Earlier chapters warned that changing random.randint(0, i) to random.randrange(i) silently breaks a shuffle. That broken version has a name: Sattolo's algorithm, published by Sandra Sattolo in 1986. It is useless as a general shuffle. For a different job it is exactly right: it picks a uniformly random permutation made of one single cycle. This chapter explains what that means, why the one-character change produces it, and when you would want it.
Cycles in a permutation
Read a permutation as a mapping from each position to the value stored there. Start at any position, follow the mapping, and you eventually come back to where you started. The positions you pass through form a cycle.
Take the array [3, 2, 0, 1]. Position 0 holds 3, position 3 holds 1, position 1 holds 2, and position 2 holds 0. Following the values gives 0 → 3 → 1 → 2 → 0. One loop covers all four positions, so this is a cyclic permutation: a permutation with exactly one cycle of length n.
By contrast, [1, 0, 3, 2] has two cycles, 0 → 1 → 0 and 2 → 3 → 2. The identity [0, 1, 2, 3] has four cycles of length 1, also called fixed points.
Counting cyclic permutations
There are (n − 1)! cyclic permutations of n items. Write the cycle starting from position 0. The first step can go to any of the other n − 1 positions, the next to any of the remaining n − 2, and so on. Every order of visiting the other positions gives a different cycle, so the total is (n − 1)!.
| n | All permutations (n!) | Cyclic permutations ((n − 1)!) |
|---|---|---|
| 3 | 6 | 2 |
| 4 | 24 | 6 |
| 5 | 120 | 24 |
| 52 | about 8.07 × 10^67 | about 1.55 × 10^66 |
The algorithm
import random
def sattolo(items):
for i in range(len(items) - 1, 0, -1):
j = random.randrange(i) # 0 <= j < i: excludes i itself
items[i], items[j] = items[j], items[i]
return items
print(sattolo(list(range(10))))The only difference from Fisher-Yates is the range for j. Fisher-Yates allows j == i, which means "leave this element where it is". Sattolo forbids that choice, so every step must swap position i with an earlier position.
A hand trace
Run Sattolo on [0, 1, 2, 3] with these random choices:
| Step | i | j chosen (from 0..i−1) | Array after swap |
|---|---|---|---|
| 1 | 3 | 1 | [0, 3, 2, 1] |
| 2 | 2 | 0 | [2, 3, 0, 1] |
| 3 | 1 | 0 | [3, 2, 0, 1] |
The result is the array from the start of the chapter, and it forms one cycle:
Why the output is always a single cycle
The argument uses induction on n, starting from the identity array [0, 1, ..., n − 1].
Base case. For n = 1 the loop does nothing, and one element on its own is a cycle of length 1. For n = 2 the loop must swap positions 1 and 0, giving [1, 0], a 2-cycle.
Inductive step. The first iteration swaps position n − 1 with some j < n − 1. Afterwards position n − 1 holds j and position j holds n − 1. The remaining iterations only touch positions 0 to n − 2.
Temporarily relabel the value n − 1 as j. Under that relabeling the prefix of length n − 1 is the identity again, and the rest of the run is exactly Sattolo on that prefix. By the induction hypothesis it produces a single cycle through positions 0 to n − 2. Somewhere in that cycle a position k points to "j".
Now undo the relabeling. Position k really points to n − 1, and position n − 1 points to j. The edge k → j has become k → n − 1 → j. Position n − 1 has been spliced into the existing cycle, so the result is still one cycle, now of length n.
Why every cycle is equally likely
There are (n − 1) × (n − 2) × … × 1 = (n − 1)! equally likely sequences of choices for j. Distinct sequences give distinct outputs. At step i the chosen j determines what lands in position i, and position i is never touched again. So the map from choice sequences to outputs is injective. It is also onto, because there are (n − 1)! sequences and (n − 1)! cyclic permutations. Each cyclic permutation therefore comes up with probability exactly 1/(n − 1)!.
This is the same counting argument used for Fisher-Yates. The difference is that Sattolo's target set has (n − 1)! members instead of n!.
Seeing the difference empirically
The script below counts outputs for n = 3 and measures cycle structure for larger n.
import random
from collections import Counter
def fisher_yates(items):
for i in range(len(items) - 1, 0, -1):
j = random.randint(0, i)
items[i], items[j] = items[j], items[i]
return items
def sattolo(items):
for i in range(len(items) - 1, 0, -1):
j = random.randrange(i)
items[i], items[j] = items[j], items[i]
return items
def cycle_count(perm):
seen = [False] * len(perm)
cycles = 0
for start in range(len(perm)):
if not seen[start]:
cycles += 1
k = start
while not seen[k]:
seen[k] = True
k = perm[k]
return cycles
def fixed_points(perm):
return sum(1 for i, v in enumerate(perm) if i == v)
print("n = 3 outputs, 60000 trials")
for name, fn in [("Fisher-Yates", fisher_yates), ("Sattolo", sattolo)]:
counts = Counter(tuple(fn([0, 1, 2])) for _ in range(60000))
print(name, dict(sorted(counts.items())))
print("\nn = 10, 20000 trials")
for name, fn in [("Fisher-Yates", fisher_yates), ("Sattolo", sattolo)]:
perms = [fn(list(range(10))) for _ in range(20000)]
avg_fixed = sum(fixed_points(p) for p in perms) / len(perms)
cycles = Counter(cycle_count(p) for p in perms)
print(name, "avg fixed points:", round(avg_fixed, 3),
"cycle counts:", dict(sorted(cycles.items())))For n = 3, Fisher-Yates prints six permutations at about 10,000 each. Sattolo prints only (1, 2, 0) and (2, 0, 1), at about 30,000 each. For n = 10, Fisher-Yates averages about 1 fixed point and produces a spread of cycle counts. Sattolo always reports 0 fixed points and exactly 1 cycle.
A single cycle is not the same as "nothing stays put"
Every Sattolo output is a derangement, meaning a permutation with no fixed points. The reverse is false. For n = 4 there are 9 derangements, but only 6 are single cycles. The other three, such as [1, 0, 3, 2], split into two 2-cycles, and Sattolo never produces them.
When you want a single cycle
| Task | Why a single cycle matters |
|---|---|
| Pointer-chasing memory benchmarks | Following `next[i]` must visit every node before repeating, otherwise the benchmark stays in a small cache-resident loop |
| Gift chain or round-robin pairing | Everyone is connected in one ring, with no closed subgroups |
| Random tour order | A walk from any start reaches every item exactly once and returns |
| Random successor function | Iterating `x = next[x]` has the maximum possible period n |
Here is the benchmark case. The array built here is a linked list in random order that visits every slot:
import random
def sattolo(items):
for i in range(len(items) - 1, 0, -1):
j = random.randrange(i)
items[i], items[j] = items[j], items[i]
return items
n = 1_000_000
next_index = sattolo(list(range(n)))
k, steps = 0, 0
while True:
k = next_index[k]
steps += 1
if k == 0:
break
print(steps == n) # True: the walk covers all n slots before returningIf you built next_index with Fisher-Yates instead, the walk starting at 0 would cover on average only about half the array before looping. The expected cycle length through a given element of a uniform random permutation is (n + 1)/2.
Practical notes
- Sattolo has the same cost as Fisher-Yates: n − 1 swaps, O(n) time, O(1) extra space.
- The advice from earlier chapters still applies. Draw
jwithout modulo bias, and remember that a generator's state size limits how many of the (n − 1)! cycles it can reach. - Most standard libraries do not ship Sattolo. Write it yourself, and put a comment on the
randrange(i)line so nobody "fixes" it back to Fisher-Yates. Put the same kind of comment on the Fisher-Yates bound so nobody breaks it in the other direction.
Exercise
Run Sattolo by hand on [0, 1, 2, 3] with choices j = 2 (at i = 3), j = 1 (at i = 2), j = 0 (at i = 1). Give the final array and write its cycle.
Show answer
i = 3, j = 2 gives [0, 1, 3, 2]. i = 2, j = 1 gives [0, 3, 1, 2]. i = 1, j = 0 gives [3, 0, 1, 2]. Following position to value: 0 → 3 → 2 → 1 → 0, a single 4-cycle.
Exercise
A teammate's shuffle passes a test asserting "no element ends at its original index" for 10,000 runs on 8 items. Why is that test evidence of a bug rather than a pass?
Show answer
A uniform shuffle leaves some element in place with probability about 1 − 1/e ≈ 63%, so across 10,000 runs it would almost certainly do so many times. Never producing a fixed point means the code only generates derangements, which is the signature of Sattolo (a randrange(i) bound instead of randint(0, i)). The test asserts the wrong property.
Exercise
For n = 4, how many outputs can Sattolo produce, and what is the probability of each? Name one derangement of 4 items that it can never produce.
Show answer
It can produce (4 − 1)! = 6 outputs, each with probability 1/6. It never produces a derangement made of two 2-cycles, for example [1, 0, 3, 2] or [2, 3, 0, 1].