Books · The Fiddler: Solutions
Chapter 28
A Loopy Holiday Gift Exchange
In a class gift exchange, everyone puts their own name in a hat and then each student draws a name. If anyone ever draws their own name, the whole class restarts. Once a valid draw is complete, the “who buys for whom” arrangement splits into loops. With five students, how likely is it that the whole class forms a single loop?
The Fiddler, Zach Wissner-Gross, November 21, 2025(original post)
Solution
Restarting whenever someone draws their own name means the final arrangement is a uniformly random derangement: a permutation with no fixed points. A single loop covering everyone is a single -cycle. There are cycles on five elements, and the number of derangements of five is , so
The computation
Enumerate every derangement of five (no one draws their own name) and count the fraction that form one big cycle, by walking the arrangement from a starting student and checking it visits all five before closing.
from itertools import permutations
from fractions import Fraction as F
ders = [p for p in permutations(range(5)) if all(p[i] != i for i in range(5))]
def single_loop(p):
seen = set(); i = 0
while i not in seen: seen.add(i); i = p[i]
return len(seen) == 5
print(F(sum(single_loop(p) for p in ders), len(ders))) # 6/11
Extra Credit
With students (a large number), how likely is a single loop, in terms of ?
Solution
A single loop is one of the full cycles, out of derangements, so Since , this becomes in the large- limit. (At it already equals to six places.)
The computation
Form the exact ratio of full cycles to derangements (built from its recurrence) for growing , and watch it close on .
from math import factorial, e
def D(n): # derangements via the standard recurrence
a, b = 1, 0
for k in range(2, n + 1): a, b = b, (k - 1)*(a + b)
return b
for N in (5, 10, 200):
print(N, factorial(N - 1)/D(N), e/N)