Chapter 85
Can You Fold All Your Socks?
You have pairs of socks and a chair holding at most socks. Draw socks one at a time at random; a sock whose partner is already on the chair forms a folded pair (freeing that spot), otherwise it takes an empty spot. What is the probability you fold all pairs without ever needing a tenth spot? Extra credit: for other numbers of pairs and spots?
Solution
The chair only ever holds unmatched socks, so the state is captured by two numbers: , the untouched pairs still in the basket, and , the lone socks on the chair. The next sock you draw is one of equally likely socks. With probability it belongs to an untouched pair and opens a new spot (needing ), and with probability it matches a sock on the chair and folds a pair, freeing a spot. Writing for the chance of finishing from that state, with once only folds remain, where running out of room ( with no sock to fold) contributes nothing. Starting empty, A few values show how demanding the chair size is: pairs succeed only of the time with spots, with , and with . The required chair grows roughly like the square root of the sock count, not linearly, so doubling the wardrobe to pairs drops even a -spot chair below a success rate.
The computation
Solve the recurrence with memoisation: from each state, weight opening a new pair and folding an open one by their draw probabilities.
from functools import lru_cache
@lru_cache(None)
def P(r, o, slots):
if r == 0: return 1.0
total = 2 * r + o; p = 0.0
if o < slots: p += (2 * r / total) * P(r - 1, o + 1, slots)
if o > 0: p += (o / total) * P(r, o - 1, slots)
return p
print(round(P(14, 0, 9), 5)) # 0.70049