এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
University Computer Science — Year 2 · স্নাতক দ্বিতীয় বর্ষ
27Randomised Algorithms
The town keeps its 120 people in a list sorted by name. A quicksort that takes the first element as its pivot, given that list again, does the worst thing it can:
names = sorted(people())
n = len(names)
for label, data, pick in [
("first pivot, sorted list", names, first),
("first pivot, shuffled list", shuffle(names, random.Random(1)), first),
("random pivot, sorted list", names, random_pivot(random.Random(1)))]:
count = [0]
assert quicksort(data, pick, count) == names
print(f"{label:27}: {count[0]:5} comparisons")
print(f"n(n - 1)/2 = {n * (n - 1) // 2}")
$ python sorted_input.py
first pivot, sorted list : 7140 comparisons
first pivot, shuffled list : 856 comparisons
random pivot, sorted list : 915 comparisons
n(n - 1)/2 = 7140
With the first element as pivot, each call splits off one element and compares it with all the others: comparisons, as the Year 1 volume counted. Sorted input is not rare, so a library cannot hope that its users avoid it. Choosing the pivot at random changes the question: there is no bad input any more, only unlucky coins, and the chapter shows they are rare. It then uses coins to make hash tables safe against an adversary, to store a set in a few bits per element, to test whether a 256-bit number is prime, and to find the weakest links of a network.
You already know
The mathematics Year 2 volume: random variables, expectation and its linearity, even when and are dependent; independent events; the geometric law, whose mean is ; Markov’s inequality, for . The Year 1 volume: quicksort and its average cost over random inputs; hash tables with chaining, and the promise that a good hash function keeps the chains short. The grade 9 volume: pseudo-random numbers, which a program draws from a seed and can draw again.
27.1 Las Vegas and Monte Carlo
Definition 27.1 (Randomised algorithm, Las Vegas, Monte Carlo)
A randomised algorithm may draw random numbers as it runs; its running time and its answer are then random variables, for each input. It is a Las Vegas algorithm if its answer is always correct and only its running time is random, and a Monte Carlo algorithm if its running time is bounded but its answer may be wrong with some probability.
Randomised quicksort is Las Vegas: the list always comes out sorted. A primality test that says “probably prime” is Monte Carlo. The listings draw their numbers from random.Random(seed): pseudo-random numbers, the same for the same seed, which is how every output of this chapter reruns identically. The analyses assume truly random draws.
Definition 27.2 (Expected running time)
The expected running time of a randomised algorithm on an input is the expectation, over its random draws, of its running time on . Its expected running time for size is the largest of these over the inputs of size .
This is not an average-case cost. An average over inputs assumes that inputs follow a law, and an adversary, or a user with a sorted list, can break it. The expected running time holds for every input: the randomness is in the algorithm, where nobody outside can choose it.
Definition 27.3 (One-sided error, amplification)
A Monte Carlo algorithm for a yes-or-no question has one-sided error if one of its answers is always right: for instance “composite” is always right and “prime” is wrong with probability at most . Amplification runs it times with independent draws and answers “prime” only if every run does.
Proposition 27.4 (Amplification)
If each run errs with probability at most , independently, the amplified algorithm is wrong with probability at most , and costs times as much.
Proof. It is wrong only if all runs are wrong, which by independence has probability at most . ∎
With and , the error is at most , far below the chance that the hardware errs during the run. A Monte Carlo algorithm whose answer can be checked cheaply becomes Las Vegas: run it until the check passes (Exercise 27.7).
27.2 Randomised quicksort and quickselect
def quicksort(a, pick, count):
"""Sort the list a of distinct keys; pick(a) chooses the pivot's index. Each element
other than the pivot is compared with it once; count[0] adds them up."""
if len(a) <= 1:
return list(a)
pivot = a[pick(a)]
count[0] += len(a) - 1
smaller = [x for x in a if x < pivot]
larger = [x for x in a if x > pivot]
return quicksort(smaller, pick, count) + [pivot] + quicksort(larger, pick, count)
def first(a):
return 0
def random_pivot(rng):
return lambda a: rng.randrange(len(a))
def shuffle(a, rng):
"""Fisher-Yates: position i receives a uniform choice among the positions >= i."""
a = list(a)
for i in range(len(a) - 1):
j = rng.randrange(i, len(a))
a[i], a[j] = a[j], a[i]
return a
Two ways remove the bad inputs: shuffle the list uniformly first, then use any fixed pivot rule; or choose each pivot uniformly at random. Both give the same law for the number of comparisons. The shuffle of the listing, due to Fisher and Yates, produces each of the orders with probability (Exercise 27.11); the tempting version that swaps each position with any position is biased (Exercise 27.2).
quicksort_trace.py. Each node is a pivot, with the number of names compared with it; its left subtree sorts the smaller names, its right subtree the larger ones. The run makes comparisons. Two names are compared exactly when one of them is an ancestor of the other.The figure shows the key to the analysis. Number the keys in sorted order. Two keys are compared at most once, when one of them is the pivot, and never again since the pivot is then set aside.
Lemma 27.5 (Comparison probability)
In randomised quicksort, for , the keys and are compared with probability .
Proof. Exercise 27.8: and stay in the same call until the first pivot drawn among , and they are compared if and only if that pivot is or . ∎
Theorem 27.6 (Randomised quicksort)
On every list of distinct keys, randomised quicksort makes on average exactly comparisons, where . This is about .
Proof. Let be if and are compared and otherwise. The number of comparisons is , and by linearity and Lemma 27.5,
grouping the pairs by , of which there are . This is . Finally . ∎
$ python quicksort_rand.py
n = 120: mean 819.9 comparisons over 1,000 runs; 2(n+1)H_n - 4n = 819.3
smallest 669, largest 1156, worst case 7140
runs above 1.5 x 819.3: 0
The proof uses no independence between the , which are far from independent: linearity of expectation is the whole tool. The output shows more than the mean: in 1,000 runs, none passed one and a half times it, and the largest is a sixth of the worst case. Bounding the spread needs more than linearity; the chapter keeps to expectations.
The same idea finds the key of a given rank without sorting: partition around a random pivot, and continue only on the side that contains the rank.
def quickselect(a, k, rng, count):
"""The key of rank k (0 for the smallest) of the list a of distinct keys."""
while True:
pivot = a[rng.randrange(len(a))]
count[0] += len(a) - 1
smaller = [x for x in a if x < pivot]
if k < len(smaller):
a = smaller
elif k == len(smaller):
return pivot
else:
k -= len(smaller) + 1
a = [x for x in a if x > pivot]
Theorem 27.7 (Quickselect)
On every list of distinct keys and every rank, quickselect makes on average at most comparisons.
Proof. Let be the largest expected number of comparisons over lists of size and ranks. The partition costs ; the pivot has rank with probability , for , and the search continues on a side of size at most . So , and . Assume for . The values run through the upper half of twice, and their sum is at most (check and ). Then . ∎
$ python quickselect.py
rank 0: mean 227.6 comparisons, largest 578; 4n = 480
rank 60: mean 373.5 comparisons, largest 758; 4n = 480
rank 119: mean 229.8 comparisons, largest 522; 4n = 480
The median is the most expensive rank, about here; the exact expectation for the median is close to for large , and is a simple bound above it.
History
Tony Hoare published Quicksort in 1961, as an algorithm of a few lines in the journal of the computing society of the time.
27.3 Universal hashing
A hash table with a fixed function such as has bad inputs too: keys that are all multiples of all land in bucket . If the keys come from outside, from names typed in a form or from packets on a network, someone can send exactly those, and every lookup becomes a walk along a list of all the keys. The cure is the same as for quicksort: choose the function at random, after the keys are fixed.
Definition 27.8 (Universal family)
A set of functions from the keys to is a universal family if for any two distinct keys , a function drawn uniformly from makes them collide with probability at most : .
Theorem 27.9 (Carter–Wegman)
Let be a prime larger than every key and . The functions , for and , form a universal family.
Proof. Fix keys in , and let , . Then , and since is prime and neither nor is a multiple of , . Conversely, given , the equations determine , which is not , and then : the map is a bijection from the functions onto the pairs . Drawing uniformly therefore draws uniformly among the pairs of distinct values. The keys collide when . For each , the values in with number at most . So the colliding pairs number at most , out of . ∎
The modular inverse used in the proof exists because is prime, the property the mathematics books prove with Bézout’s identity; the program never computes it.
Corollary 27.10 (Short chains)
Store keys in a table of buckets with chaining, with a function drawn from a universal family. For every key of the table, the expected length of its chain is at most , where . For a key not in the table, the expected length of the chain it lands in is at most .
Proof. The chain of holds and the keys with . Its length is , where is on a collision, and . By linearity, the expectation is at most . For a key not in the table, the same sum has terms and no . ∎
This is the promise the Year 1 volume made for hash tables, now kept for every set of keys, with the randomness in the choice of the function. The listing attacks both kinds of function with keys that are all multiples of .
P = 2**31 - 1 # a prime larger than every key
def draw(m, rng):
"""A random member of the family h(x) = ((a x + b) mod p) mod m."""
a, b = rng.randrange(1, P), rng.randrange(P)
return lambda x: (a * x + b) % P % m
def chains(keys, h, m):
lengths = [0] * m
for x in keys:
lengths[h(x)] += 1
return lengths
$ python universal_hash.py
n fixed: longest | universal, 1,000 draws: longest (median) key's chain bound
200 200 | 5 1.991 1.995
400 400 | 5 2.000 1.998
600 600 | 5 1.998 1.998
800 800 | 5 1.999 1.999
1000 1000 | 5 1.999 1.999
The measured average chain of a key matches the bound to within the noise of 1,000 draws: for these keys the bound is reached. The adversary has not disappeared: once a function is drawn, keys exist that collide under it. A server must therefore keep its draw secret, and libraries of several languages draw a secret seed for their string hashing when the program starts.
History
Lawrence Carter and Mark Wegman defined universal classes of hash functions in 1979, with the family of Theorem 27.9 among their examples.
27.4 Bloom filters
A set of a million long strings takes megabytes as a hash table. Often one only needs to answer “certainly not in the set” quickly, and to look further for the rest: a browser checking addresses against a list of known bad sites, a database checking whether a disk block might hold a key before reading it.
Definition 27.11 (Bloom filter, false positive)
A Bloom filter is an array of bits, all at first, and hash functions with values in . Adding a key sets the bits to . A lookup of answers “present” if its bits are all . A false positive is a lookup that answers “present” for a key that was never added.
A key that was added always finds its bits set: there are no false negatives. Keys cannot be removed, since a bit may be shared.
class Bloom:
def __init__(self, m, k, rng):
self.bits = bytearray(m)
self.hashes = [draw(m, rng) for _ in range(k)]
def add(self, x):
for h in self.hashes:
self.bits[h(x)] = 1
def __contains__(self, x): # never wrong for a key added; sometimes for others
return all(self.bits[h(x)] for h in self.hashes)
$ python bloom_small.py
add Ada: bits [15, 5, 11]
add Ben: bits [8, 10, 6]
add Cy : bits [9, 6, 11]
filter: 0000011011110001
36 other first names looked up: 3 false positives
Aarav: bits [14, 15, 9], in filter: False
Hana: bits [10, 11, 6], in filter: True
Proposition 27.12 (False-positive rate)
Assume that the hash values of added keys, and the values of a key looked up, are independent and uniform on . After keys, a given bit is still with probability , and if the bits are treated as independent, a key not added is a false positive with probability about
For a given ratio this is smallest for , where it is .
Proof. Each of the values misses a given bit with probability , independently; and for large . A key not added is a false positive when its bits are ; treating them as independent gives the formula. Write , so that and the logarithm of the rate is . The product is symmetric in and , and largest at , which minimises the rate: then and the rate is . ∎
The independence of the bits is an approximation; the measurement shows it is a good one. With 8 bits per key the best rate is about , with 10 bits about , whatever the length of the keys.
$ python bloom.py
n = 1000 keys, m = 8000 bits; 100,000 other keys queried
k measured (1 - e^(-kn/m))^k
1 0.1177 0.1175
2 0.0486 0.0489
3 0.0300 0.0306
4 0.0241 0.0240
5 0.0223 0.0217
6 0.0214 0.0216
7 0.0241 0.0229
8 0.0246 0.0255
9 0.0280 0.0292
10 0.0321 0.0342
best k = (m/n) ln 2 = 5.55
In practice
Burton Bloom described the structure in 1970, for a dictionary too large for memory. Storage engines that keep sorted files of keys on disk put a Bloom filter in front of each file, so that most lookups of absent keys never read the file.
27.5 Primality
Public-key cryptography needs random primes of hundreds of bits. Trial division up to takes about steps for a 256-bit number. A randomised test takes a few modular exponentiations, each multiplications by repeated squaring.
Definition 27.13 (Fermat witness, Carmichael number)
Let be odd and . If , then is a Fermat witness for ; otherwise passes for the base . A Carmichael number is an odd composite number that passes for every base coprime to it.
Proposition 27.14 (The Fermat test)
If is prime, it passes for every base. If is composite and has at least one Fermat witness coprime to it, then at least half of the bases coprime to are Fermat witnesses.
Proof. The first part is Fermat’s little theorem, from the mathematics books. For the second, let be a witness coprime to and the bases coprime to for which passes. The products are coprime to and distinct, since is invertible modulo . Each is a witness: . So there are at least as many witnesses as passing bases. ∎
The Carmichael numbers escape the second part, and they exist: is the smallest. A sharper test asks more of a prime.
Definition 27.15 (Miller–Rabin witness)
Let be odd, and write with odd. A base is a Miller–Rabin witness for if and for every .
A prime has no Miller–Rabin witness. The sequence ends with , by Fermat, and each term is the square of the one before. If , then divides , so : the term before the first , if there is one, is .
def miller_rabin_passes(n, a):
"""Write n - 1 = 2^s d with d odd. A prime n passes for every base: either
a^d = 1, or one of a^d, a^(2d), ..., a^(2^(s-1) d) is -1 mod n."""
s, d = 0, n - 1
while d % 2 == 0:
s, d = s + 1, d // 2
x = pow(a, d, n)
if x in (1, n - 1):
return True
for _ in range(s - 1):
x = x * x % n
if x == n - 1:
return True
return False # a is a witness: n is composite
def is_probable_prime(n, rounds, rng):
"""Monte Carlo: 'composite' is always right; 'prime' is wrong with probability
at most 4^-rounds."""
if n < 4:
return n in (2, 3)
if n % 2 == 0:
return False
return all(miller_rabin_passes(n, rng.randrange(2, n - 1)) for _ in range(rounds))
Theorem 27.16 (Miller–Rabin)
If is odd and composite, at most a quarter of the bases are not Miller–Rabin witnesses. So rounds with independent uniform bases answer “prime” for a composite number with probability at most .
Proof. Admitted at this level. ∎
The proof uses the structure of the group of units modulo and the Chinese remainder theorem, which the mathematics books develop. The second sentence follows by Proposition 27.4.
$ python fermat_mr.py
n = 561: Fermat passes 318 of 318 coprime bases; Miller-Rabin passes 8 of 558 bases
n = 1105: Fermat passes 766 of 766 coprime bases; Miller-Rabin passes 28 of 1102 bases
n = 1729: Fermat passes 1294 of 1294 coprime bases; Miller-Rabin passes 160 of 1726 bases
n = 1009: Fermat passes 1006 of 1006 coprime bases; Miller-Rabin passes 1006 of 1006 bases
The three Carmichael numbers pass the Fermat test for all their coprime bases, and the Miller–Rabin test catches them with more than of the bases. To draw a random prime of 256 bits, draw random odd numbers of 256 bits until one passes. By the prime number theorem, a number near is prime with probability about , an odd one about ; the number of draws follows a geometric law of mean about .
$ python random_prime.py
last prime found: f231cb4067aef03fb1b912948cdfa2fcf29aa45fdf...
mean trials over 200 primes: 94.7; (ln 2^256) / 2 = 88.7
fewest 1, most 512
The mean, 94.7, is within the noise of 200 draws of the model’s : a geometric law of mean 88 has a standard deviation near 88, so the mean of 200 draws varies by about . The largest, 512, shows how long the tail of a geometric law is.
History
Gary Miller published in 1976 a test that is correct if a form of the Riemann hypothesis holds; Michael Rabin made it probabilistic, with a proven error bound and no hypothesis, in a paper published in 1980.
27.6 Random choices that approximate
Satisfying many clauses. Some problems are hard to solve exactly but easy to solve well by tossing coins. In the satisfiability problem of Chapter 24, a formula is a conjunction of clauses, and one may ask for an assignment that satisfies as many clauses as possible.
Proposition 27.17 (A random assignment)
Give each variable the value true or false with probability , independently. A clause of literals on distinct variables is satisfied with probability . So the expected number of satisfied clauses is at least half of them, and at least three quarters if every clause has two literals or more.
Proof. The clause is false only if each of its literals is false, which happens with probability since the variables are distinct and independent. Summing over the clauses with linearity gives the expected number, and , or when . ∎
$ python maxsat.py
200 clauses: mean satisfied 149.7, expected 150.0, best of 1,000 runs 169
200 clauses: mean satisfied 152.5, expected 152.5, best of 1,000 runs 168
An expectation is reached by some outcome: an assignment satisfying at least three quarters of the 2-literal clauses always exists, which the proposition proves without exhibiting one.
Karger’s minimum cut. A cut of an undirected graph splits its vertices into two non-empty parts; its size is the number of edges between them. Unlike the cuts of Chapter 26, no source or sink is fixed: the question is the smallest cut of all.
Definition 27.18 (Edge contraction)
In a multigraph (a graph that may have several edges between two vertices), contracting an edge replaces and by a single vertex, keeps every other edge of or with its end moved to the new vertex, and removes the edges between and , which would become loops.
Karger’s algorithm contracts a uniformly random edge until two vertices remain, and returns the edges between them. Each vertex then stands for a set of original vertices, and the edges between the two are a cut of the original graph.
def contract(vertices, edges, rng, log=None):
"""Contract random edges until two super-vertices remain. Taking the edges in a
random order and skipping those inside a super-vertex picks each contraction
uniformly among the edges left. Returns the cut: the edges between the two."""
parent = {v: v for v in vertices}
left = len(vertices)
order = list(edges)
rng.shuffle(order)
for u, v in order:
if left == 2:
break
ru, rv = find(parent, u), find(parent, v)
if ru != rv: # an edge inside a super-vertex would be a self-loop
parent[ru] = rv
left -= 1
if log is not None:
log.append((u, v))
side = {v for v in vertices if find(parent, v) == find(parent, vertices[0])}
return [(u, v) for u, v in edges if (u in side) != (v in side)], side
def karger(vertices, edges, runs, rng):
"""The smallest cut found in independent runs."""
return min((contract(vertices, edges, rng) for _ in range(runs)),
key=lambda r: len(r[0]))
The listing does not build the multigraph. It takes the edges in a random order and contracts each one unless its ends are already merged. An edge whose ends are merged is exactly a loop, so the first edge of the order that is not a loop is uniform among the edges that remain: the same law as the algorithm.
$ python karger_demo.py
contracted: bd cd eh ac gh fh
cut of 2 edges: de cf | one side: abcd
minimum cut found in 2147 of 10,000 runs; bound 2/(n(n-1)) = 0.0357
Theorem 27.19 (Karger)
Let be a minimum cut of a connected multigraph with vertices. One run of the contraction algorithm returns exactly with probability at least . With independent runs, keeping the smallest cut found, it misses every minimum cut with probability at most .
Proof. Let . The run returns if it never contracts an edge of : then the two final vertices are the two sides of . Every vertex of the multigraph has degree at least at every stage, since the edges at a vertex form a cut of the original graph (its set of original vertices against the rest). With vertices left there are therefore at least edges, and a uniform edge is in with probability at most , if no edge of was contracted yet. The stages have vertices, so the run avoids with probability at least
the product telescoping. With independent runs, all of them miss with probability at most , using ; this is for the of the statement. ∎
The bound is for one given minimum cut, in the worst graph. The measured success in Output 27.10, about , is six times the bound . A run is a near-linear pass over the edges, and runs give a total far above the cost of the best methods, but the algorithm is three lines and its analysis one product.
History
David Karger published the contraction algorithm in 1993.
27.7 Exercises
Exercise 27.1 ★
passes the Miller–Rabin test for 160 of the 1,726 bases from to (Output 27.7). What does the -round test of Listing 27.6 answer for 1729, and with which probabilities, for ? Compare with exo_monte_carlo.py.
Solution
Solution of Exercise 27.1.
Each round draws a base uniformly in and 1729 passes with probability . The test answers “composite” unless all rounds pass, so it answers “prime”, wrongly, with probability : about , , and for . “Composite” is always right.
$ python exo_monte_carlo.py
k = 1: 'prime' in 9414 of 100,000 runs; (0.0927)^k x 100,000 = 9270.0
k = 2: 'prime' in 912 of 100,000 runs; (0.0927)^k x 100,000 = 859.3
k = 3: 'prime' in 86 of 100,000 runs; (0.0927)^k x 100,000 = 79.7
k = 5: 'prime' in 1 of 100,000 runs; (0.0927)^k x 100,000 = 0.7
Exercise 27.2 ★
A shuffle swaps each position with a position drawn uniformly among all . For , count the sequences of choices that produce each order, and explain from the numbers and why no such shuffle can be uniform. Check with exo_shuffle.py.
Solution
Solution of Exercise 27.2.
$ python exo_shuffle.py
swap with any position: 27 choices; 012:4 021:5 102:5 120:5 201:4 210:4
Fisher-Yates : 6 choices; 012:1 021:1 102:1 120:1 201:1 210:1
The 27 equally likely sequences give the orders , , four times each and the three others five times. No shuffle that makes uniform choices among can be uniform for : each order would need sequences, which is not a whole number. Fisher–Yates makes choices, one per order.
Exercise 27.3 ★
Write a function that reads a stream of unknown length once and returns of its items, each set of items being equally likely, keeping only items in memory. Check it exhaustively for and .
Solution
Solution of Exercise 27.3.
def reservoir(stream, k, choose):
"""Keep the first k items; item i (from 0) then replaces a random kept item with
probability k/(i + 1). choose(i) returns a uniform number in 0..i."""
sample = []
for i, x in enumerate(stream):
if i < k:
sample.append(x)
else:
j = choose(i)
if j < k:
sample[j] = x
return sample
$ python exo_reservoir.py
360 choice sequences, 15 samples of 2 out of 6, each obtained {24} times
5 lines out of 10,000: ['loan 7149', 'loan 3669', 'loan 4689', 'loan 6152', 'loan 7994']
By induction on : after the items , every set of of them is the sample with probability . Item enters with probability , replacing a uniform one of the . A set of items among that does not contain is the new sample if it was the old one and did not enter: . A set containing is the new sample if the old one was plus one of the other items, entered, and replaced that item: .
Exercise 27.4 ★
A trial succeeds with probability , independently of the others. Prove that the expected number of trials up to the first success is . Deduce the expected number of odd 256-bit numbers drawn in Output 27.8, taking the probability that one is prime to be .
Solution
Solution of Exercise 27.4.
Let be the expectation. The first trial succeeds with probability ; otherwise one trial is spent and the process starts again: , so (the sum gives the same). With , ; Output 27.8 measured , one standard error of the mean of 200 draws ( divided by , about 6) above it: sampling noise.
Exercise 27.5 ★★
. Show that (), so that base 2 does not reveal 341, but base 3 does. Count the bases that do not reveal it, and show that Miller–Rabin with base 2 does. Check with exo_341.py.
Solution
Solution of Exercise 27.5.
, so : base 2 passes. Base 3 does not.
$ python exo_341.py
298 coprime bases in 2..339; Fermat liars: 98, the first ones [2, 4, 8, 15, 16, 23, 27, 29]
2^340 mod 341 = 1; 3^340 mod 341 = 56
2^85 mod 341 = 32, 2^170 mod 341 = 1; Miller-Rabin with base 2 passes: False
98 of the 298 bases coprime to 341 pass, fewer than half, as Proposition 27.14 requires. For Miller–Rabin, : , not , and , not , so 2 is a witness. The square root of that is neither nor proves 341 composite: divides without dividing either factor, and indeed and are its factors.
Exercise 27.6 ★★
A Bloom filter takes its positions as from a single function , to save time. Compare its false-positive rate with the filter of Listing 27.5 using exo_bloom_bug.py, and explain the difference.
Solution
Solution of Exercise 27.6.
$ python exo_bloom_bug.py
Bloom k = 6: 4216 bits set, false positives 0.0216
Consecutive k = 6: 4289 bits set, false positives 0.2548
Both set about the same number of bits, but the consecutive version sets them in runs of six. A key not added is rejected only if one of its six bits is ; its bits are consecutive too, and inside a run, or across two runs that touch, they are all . The six tests are no longer independent: once falls in a run, the next bits are very likely set. The rate, , is closer to that of a single test than to .
Exercise 27.7 ★★
Modulo a prime , half the numbers are not squares, and Euler’s criterion recognises them: . Write a Monte Carlo algorithm that returns a non-square after at most draws and is wrong with probability , then a Las Vegas one that is never wrong. What is its expected number of draws?
Solution
Solution of Exercise 27.7.
$ python exo_las_vegas.py
Monte Carlo, k = 1: wrong in 5056 of 10,000 runs; 10,000 x 2^-k = 5000.0
Monte Carlo, k = 3: wrong in 1296 of 10,000 runs; 10,000 x 2^-k = 1250.0
Monte Carlo, k = 10: wrong in 5 of 10,000 runs; 10,000 x 2^-k = 9.8
Las Vegas: always right; mean draws 2.028, most 14
Each draw is a non-square with probability , independently. The Monte Carlo version stops at the first draw that passes the check, or after draws, and is wrong only if all fail: probability . The Las Vegas version draws until the check passes; its number of draws follows a geometric law of mean (Exercise 27.4), and the measured mean is .
Exercise 27.8 ★★
Prove Lemma 27.5.
Solution
Solution of Exercise 27.8.
Let , of keys. As long as no pivot has been drawn from , the whole of stays in one call: a pivot smaller than or larger than sends all of to the same side. Consider the first pivot drawn from . It is drawn uniformly from the list of the call, which contains , so given that it falls in it is uniform on . If it is or , it is compared with every key of the call, the other one among them. Otherwise it lies strictly between them, sends to the left and to the right, and they are never in the same call again. So they are compared with probability .
Exercise 27.9 ★★
On the graph of Output 27.10, run Karger’s algorithm times and keep the smallest cut, for , and measure how often it is the minimum cut. Compare with for the measured and for the bound.
Solution
Solution of Exercise 27.9.
$ python exo_karger_rep.py
r success 1-(1-p)^r 1-(1-2/(n(n-1)))^r
1 0.216 0.215 0.036
2 0.383 0.383 0.070
5 0.701 0.701 0.166
10 0.918 0.911 0.305
20 0.995 0.992 0.517
With independent runs, the best of is the minimum cut unless every run misses it: . The measured values follow this law with the measured . The bound, , predicts much less: it promises only after about runs, where 20 are enough on this graph.
Exercise 27.10 ★★★
Store keys in buckets with a function drawn from a universal family, and let be the longest chain. Show that , where is the length of chain , that the expectation of this sum is at most , and deduce . Why does Output 27.4 show far less?
Solution
Solution of Exercise 27.10.
The longest chain contributes to the sum, and the other terms are non-negative. The sum counts the ordered pairs of distinct keys in the same bucket, so its expectation is . Since , with the sum, and (the variance of is non-negative), so . Universality bounds only pairs of keys, and some universal families reach this order of growth; the family of Theorem 27.9 behaves on these keys almost like a random function, for which the longest chain grows like , about 5 here.
Exercise 27.11 ★★★
Prove that the shuffle of Listing 27.2 produces each of the orders with probability .
Solution
Solution of Exercise 27.11.
The shuffle makes choices, the -th uniform among values, independently: equally likely sequences. Each sequence gives one order, and each order comes from exactly one sequence: given the final order, position must hold its final element, which fixes the first choice (the position where that element was); the list after the first swap is then fixed, and the same argument applies to position and the rest. A bijection between equally likely sequences and the orders gives each order the probability . For , the second line of Exercise 27.2’s output shows it.
Exercise 27.12 ★★★
A skip list keeps its keys in a sorted linked list, and each key also in the lists of levels with probability for each further level, independently. Implement search and insertion, and measure the number of nodes a search looks at for against .
Solution
Solution of Exercise 27.12.
def search(self, key):
"""The largest key <= key at level 0, and the number of nodes looked at."""
level, node, looked = len(self.head) - 1, None, 0
while level >= 0:
nxt = (node[level + 1] if node else self.head[level])
while nxt is not None and nxt[0] <= key:
node, looked = nxt, looked + 1
nxt = node[level + 1]
looked += 1 # the node that stopped us, or the end of the level
level -= 1
return node, looked
$ python exo_skiplist.py
n levels nodes looked at (mean of 1,000 searches) 2 log2 n
1024 11 20.7 20.0
4096 11 21.8 24.0
16384 15 28.7 28.0
65536 21 35.8 32.0
The number of levels is about , since a key reaches level with probability . Followed backwards, a search goes up a level each time the node reached was promoted, with probability , and left otherwise: on average two steps per level, so about nodes, as measured. The insertion follows the same path and links the new node on each of its levels.
27.8 Problem: The weakest links of the friendship network
Problem 27.1
Weekend problem — The weakest links of the friendship network
The town records the friendships of its people in a table. The program below finds the groups, then runs Karger’s algorithm 10,000 times on the larger group, and on its core: the people left after setting aside, again and again, those with fewer than two friends left.
$ python friends_problem.py
39 people have friends, 50 friendships; two groups of 29 and 10 with no friendship between
the smaller group's friendships: 15-27 16-19 16-21 16-27 17-19 17-23 19-23 22-27 23-24 23-26 23-27
the larger group: 29 people, 39 friendships; smallest cut 1, found in 7,287 of 10,000 runs
bound 2/(n(n-1)) = 0.0025; 7 different minimum cuts found, the most frequent:
one side [18]: 1124 runs
one side [18, 20]: 1056 runs
one side [25]: 1056 runs
its core: 22 people, 32 friendships; smallest cut 2, found in 6,995 of 10,000 runs
bound 2/(n(n-1)) = 0.0043; 15 different minimum cuts found, the most frequent:
one side [36]: 563 runs
one side [28, 29, 30, 32, 34, 36, 37, 38, 39]: 558 runs
one side [7]: 518 runs
the cut that sets apart the 9 people [28, 29, 30, 32, 34, 36, 37, 38, 39]: 558 runs
Part I — Contractions by hand.
- The table has friendships for 39 of the 120 people. What is the minimum cut of the network of these 39 people, and what does Karger’s algorithm return on it?
- Draw the smaller group, with its 11 friendships. Which people have a single friend?
- What is the minimum cut of the smaller group, and how many minimum cuts does it have?
- Contract, in this order, 16-19, 17-23, 19-23, 23-27, 15-27, 22-27, 23-24, 23-26. Which two vertices are left, and what cut is returned?
- Give an order of contractions that returns a cut of size 2 or more.
- On a graph with a vertex of degree 1, can Karger’s algorithm return a cut of size 1 that does not separate that vertex? Discuss.
Part II — The bound.
- Why does every vertex of the multigraph have degree at least at every stage, when is the size of a minimum cut?
- Prove that the product equals .
- Compute the bound for the larger group and for its core, and compare with the lines of Output 27.11.
- Show that a graph on vertices has at most minimum cuts. (Each one is found with probability at least by the same run.)
- Give a graph with exactly minimum cuts: a cycle of vertices.
- Why is the measured success on the larger group, about , so far above the bound?
Part III — Amplification.
- How many runs does Theorem 27.19 require to find a minimum cut of the core with probability at least ?
- Using the measured rate of the cut that sets apart nine people, in , how many runs give for that cut?
- The program keeps the smallest cut over the runs. Why is the answer of runs never larger than the answer of one run, and when is it wrong?
- Is the amplified algorithm Las Vegas or Monte Carlo? Can its answer be checked cheaply?
- Compare the cost of runs with that of computing a maximum flow from one vertex to each of the others, as in Chapter 26.
- Describe how stopping the contractions at about vertices and recursing twice could reduce the number of repetitions needed (no proof).
Part IV — What the measurements say.
- The larger group has 7 minimum cuts. Identify them in the friendship table: they are the friendships whose removal splits the group.
- The seven are found about equally often, close to runs each. What do the other runs return, and why is that not an error of the program?
- In the core, the minimum cut is 2. Which two friendships join the nine people to the others?
- The core has 15 minimum cuts found. How many of them separate a single person, and why do those people have exactly two friends in the core?
- The nine people’s cut is found in of the runs and the bound is . State the problem’s result: Karger’s bound, success at least , against the rates measured on the town’s network.
- If the town wanted the weakest link between two real communities rather than a person with few friends, what should it change in the question?
Solution
Solution of Problem 27.1.
1. : the two groups have no friendship between them. Contractions never join the groups, so every run ends with the two groups and returns the empty cut.
2. A cycle 16, 19, 23, 27; a triangle 17, 19, 23; and the people 15 and 22 (friends of 27), 21 (of 16), 24 and 26 (of 23), each with a single friend.
3. , and there are five minimum cuts, one for each of the five people with a single friend: their friendships are the only ones whose removal splits the group.
4. The contractions build one vertex from all but 21; the two vertices are 21 and the rest, and the cut is the friendship 16-21.
5. Contract 16-21 first, then 15-27, 22-27, 23-27, 17-23, 19-23, 23-24, 23-26: the two vertices are and the rest, joined by 16-19 and 16-27.
6. Yes: any of the five minimum cuts may come out, and each separates a different person. The algorithm finds a minimum cut, not a particular one.
7. A vertex of the multigraph stands for a set of people, and its edges are the friendships between and the rest: a cut of the original graph, so at least .
8. : the numerators are and the denominators , which leaves .
9. and , as printed; the measured rates of each single cut, about and to , are far above.
10. The events “the run returns ”, for different minimum cuts , are disjoint, and each has probability at least ; their probabilities add up to at most .
11. In a cycle every vertex has degree 2, every cut has at least 2 edges, and any 2 of the edges form a cut of size 2 (the two arcs between them): minimum cuts.
12. The bound is for one given minimum cut in the worst graph. The group has 7, each found about of the time; and its many people with one or two friends make most contractions harmless.
13. runs.
14. for runs.
15. It is the smallest over the runs, so at most any single one. It is wrong when no run found a minimum cut; the answer is then a cut, but not a minimum one.
16. Monte Carlo: the running time is fixed and the answer may be too large. Checking that a cut is minimum needs a minimum-cut computation, so there is no cheap check.
17. One maximum flow by Edmonds–Karp costs for edges, and of them, from a fixed vertex to each other one, find a minimum cut (the fixed vertex is on one side, some other on the other side): . The runs of almost-linear cost give up to the cost of the unions, which is smaller when is large.
18. Most of the risk is in the last contractions, when is large. Contracting to about vertices keeps a given minimum cut with probability about ; recursing twice on the result, independently, spends the repetitions where the risk is.
19. The seven friendships 4-9, 12-20, 18-20, 25-37, 29-31, 33-35 and 33-39; the program prints the smaller side of the three most frequent: 18 (friend of 20 only), 25, and 18 with 20.
20. Cuts of 2 or more friendships: a run fails when it contracts one of the seven friendships before the end. It still returns a cut, only not a minimum one; the minimum over several runs corrects it.
21. 1-28 and 5-37: from the larger part, 28 is a friend of 1, and 37 of 5.
22. Ten, those with exactly two friends in the core: a cut that separates one person consists of that person’s friendships, so it has size 2 exactly when the person has two.
23. The result: Karger’s bound guarantees that a given minimum cut is found with probability at least , for the 22 people of the core; the cut that sets apart nine people is found in of the runs, and a minimum cut of some kind in about .
24. Ask for a cut whose two sides both have at least a given number of people, or divide the size of a cut by the size of its smaller side; the single people with two friends then stop being the answer. That problem is harder, and contraction alone no longer solves it.