Lesson goal: The coin sequence race

Previous: Rolling doubles and going to jail | Home | Next: Introduction: Make a flashing animation

Here is a coin game that seems completely fair on the surface, but is secretly heavily biased.

Suppose you and a friend continuously flip a single coin, generating a growing string like T-H-T-T-H-H....

- Player 1 wins as soon as the sequence Heads then Heads (HH) appears.
- Player 2 wins as soon as the sequence Tails then Heads (TH) appears.

On any pair of flips, both HH and TH have an identical 1 in 4 ($25\%$) probability. So you would expect each player to win roughly $50\%$ of the races, right?

Let's test this in Lua by simulating $5{,}000$ games.

Prepare for a surprise: Player 2 (TH) will win around 75% of the time!

Why? Think about it: if the coin ever lands on Tails even once before HH, Player 1 (HH) can never win on the next flip. To get HH, a Head must occur, which means a Tail followed by a Head (TH) happens first! The only way Player 1 can win is if the very first two flips of the entire game happen to be HH ($1/4 = 25\%$).

Now you try. What if the race is between Heads-Tails-Tails (HTT) and Tails-Heads-Tails (THT)? Try modifying the code to check three-letter patterns!

Type your code here:


See your results here: