Chapter 113
How Long Will You Be Stuck at the Bar?
A marker sits at on the integer number line, and a fair coin is flipped over and over. Heads moves the marker one step in the positive direction, tails one step in the negative direction. You hold the winning number (a negative integer) and your friend holds the winning number (a positive integer). You win if the marker reaches first, and your friend wins if it reaches first. How many flips, on average, does a complete game take?
The Riddler, FiveThirtyEight(original post)
Solution
The whole problem turns on one fact about averages: the expected time to finish, written as a function of the marker’s position, bends at a constant rate. That forces it to be a parabola, and two known values pin the parabola down.
Measure position by how far the marker sits to the right of your number . Call that , so runs from (the marker is on , you have won) to (the marker is on , your friend has won). The game starts at the origin, which is . Let be the expected number of flips still to come from position . The two ends are settled: because the game is already over there.
For an interior position, one flip happens for certain, and then the marker is equally likely to sit at or : Rearranging puts the structure on display: The left side is the second difference of , the discrete version of a second derivative. A second difference equal to a constant means is a quadratic whose leading coefficient is : for some constants and . The boundary values fix them. From we get . From we get , so . Hence This is worth reading aloud: the expected length from position is the product of the two gaps, the distance to your barrier and the distance to your friend’s. The game begins at , where the gaps are and , so A short game on one side ( small) keeps the whole thing short no matter how far away the other barrier is, which matches the intuition that you almost always drift to the near wall first.
The computation
Play the actual game. Start the marker at , flip a fair coin until it hits or , count the flips, and average over many games. The mean should land on .
import random
random.seed(0)
def game_length(X, Y):
pos, flips = 0, 0
while -X < pos < Y:
pos += 1 if random.random() < 0.5 else -1
flips += 1
return flips
for X, Y in [(3, 4), (5, 7), (2, 9)]:
trials = 400_000
mean = sum(game_length(X, Y) for _ in range(trials)) / trials
print(f"X={X} Y={Y}: simulated={mean:6.3f} X*Y={X*Y}")
# X=3 Y=4: simulated=11.978 X*Y=12
# X=5 Y=7: simulated=34.955 X*Y=35
# X=2 Y=9: simulated=18.010 X*Y=18