Permutations and Records
Many probability questions come down to counting arrangements. A permutation of objects is an ordering of them; there are of them. The counting rules themselves are covered in Discrete Mathematics; this lesson uses them to answer probability questions about random orderings.
Random permutations
A random permutation is one chosen uniformly from all , each with probability . random.shuffle produces one (by the Fisher–Yates algorithm, see Card Shuffling). Because every ordering is equally likely, probabilities are counts divided by :
- the probability that a given object ends up in a given position is ;
- the probability that objects and appear with before is by symmetry.
Birthdays, again
The probability that people all have different birthdays (365 equally likely days) is the number of ordered selections of distinct days, , over . Python's math.perm(n, k) counts these -permutations directly:
from math import perm
def p_shared(k, days=365):
return 1 - perm(days, k) / days ** k
for k in [10, 23, 30, 40, 57]:
print(f"{k} people: P(some shared birthday) = {p_shared(k):.4f}")10 people: P(some shared birthday) = 0.1169
23 people: P(some shared birthday) = 0.5073
30 people: P(some shared birthday) = 0.7063
40 people: P(some shared birthday) = 0.8912
57 people: P(some shared birthday) = 0.9901
The computing consequences (hash collisions, random IDs) are in Hashing and the Birthday Bound.
Records
Look at a random permutation from left to right. Position is a record if its value is larger than everything before it. (Think of yearly rainfall: a record year beats all previous ones.) How many records should we expect?
The value at position is the largest of the first values with probability , because among the first values each is equally likely to be the largest. So the expected number of records is
using linearity of expectation. For years of data that is only about 5.2 records.
import random
rng = random.Random(3)
def records(seq):
best, count = float("-inf"), 0
for x in seq:
if x > best:
best, count = x, count + 1
return count
for n in [10, 100, 1000]:
trials = 5000
total = 0
for _ in range(trials):
p = list(range(n))
rng.shuffle(p)
total += records(p)
H = sum(1 / i for i in range(1, n + 1))
print(f"n={n:5d} average records {total / trials:.3f} H_n = {H:.3f}")n= 10 average records 2.942 H_n = 2.929
n= 100 average records 5.211 H_n = 5.187
n= 1000 average records 7.452 H_n = 7.485
Fixed points and cycles
A fixed point of a permutation is a position with . The expected number of fixed points is exactly 1 for every (each position is fixed with probability ). The probability of no fixed point (a derangement) tends to , as shown in Rules of Probability.
import random
from collections import Counter
rng = random.Random(5)
n, trials = 8, 50_000
dist = Counter()
for _ in range(trials):
p = list(range(n))
rng.shuffle(p)
dist[sum(p[i] == i for i in range(n))] += 1
print("fixed points:", {k: round(dist[k] / trials, 3) for k in sorted(dist)})
print("mean:", round(sum(k * c for k, c in dist.items()) / trials, 3))fixed points: {0: 0.366, 1: 0.366, 2: 0.188, 3: 0.06, 4: 0.016, 5: 0.003, 6: 0.001}
mean: 1.006
The distribution of fixed points is close to a Poisson distribution with mean 1: probabilities near , that is 0.368, 0.368, 0.184, 0.061, …
In software
Random permutations drive A/B test assignment, randomized algorithms (random pivot order in quicksort), load balancing and the shuffle button of every music player. The records argument also analyses how often a running maximum is updated in a stream, the expected number of times "if x > best: best = x" executes: , logarithmic.
Exercises
Exercise 1: Seating
Six people sit in a row at random. What is the probability that Ana and Ben sit next to each other?
Answer
.
Solution
Treat Ana and Ben as a block: arrangements of block and others, times 2 orders inside the block: out of .
Exercise 2: Last is largest
In a random permutation of , what is the probability that the last position is a record?
Answer
.
Solution
The last value is a record exactly when it is the maximum , which is in the last position with probability .
Exercise 3: Secretary problem (code)
You see candidates in random order and must accept or reject each on the spot. Strategy: reject the first , then accept the first one better than all of them. Simulate the probability of picking the very best for .
Answer
(about ) does best, near 0.37.
Solution
The optimal cutoff is about , with success probability about .
import random
rng = random.Random(7)
n, trials = 50, 20_000
def success(r):
wins = 0
for _ in range(trials):
p = list(range(n))
rng.shuffle(p)
bar = max(p[:r])
chosen = next((x for x in p[r:] if x > bar), None)
wins += chosen == n - 1
return wins / trials
for r in [5, 18, 30]:
print(r, success(r))5 0.2403
18 0.37255
30 0.31415
Test yourself
What is the expected number of fixed points of a random permutation of items?
- 1
The expected number of records in a random sequence of length grows like…
- a constant