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:
To complete this lesson: In Penney's coin race, Player 1 is racing for HH and Player 2 is racing for TH.
Initialize the target sequence variables near the top of the code:
1. For Player 1 (HH): set p1_first = "H" and p1_second = "H".
2. For Player 2 (TH): set p2_first = "T" and p2_second = "H".
Then click Run to see who wins the race! Notice how Player 2 crushes Player 1 approximately 3 to 1 ($75\%$ vs $25\%$). (Click Example above to see the full solution).
Share your code
Show a friend, family member, or teacher what you've done!