Q.Two friends decide who gets the last slice of a cake by flipping a coin five times. The first person to win three flips wins the cake. An input of 1 means player 1 wins a flip, and a 2 means player 2 wins a flip. Design an algorithm to determine who takes the cake?
Track two win-counters and keep reading flip results until one counter reaches 3 — that player wins the cake; at most 5 flips are ever needed.
The idea (best-of-five). "First to win three flips" is a condition-controlled loop, not a fixed count of 5: the contest can end after 3, 4 or 5 flips. In any 5 flips one player is guaranteed at least 3 wins, so the loop always terminates within 5 inputs. The state we must remember is just two counters.
Algorithm
WHO_TAKES_THE_CAKE
Step 1: SET count1 = 0, count2 = 0
Step 2: WHILE count1 < 3 AND count2 < 3, REPEAT Steps 3-4
Step 3: INPUT flip (1 = player 1 won the flip, 2 = player 2)
Step 4: IF flip == 1 THEN count1 = count1 + 1
ELSE count2 = count2 + 1
Step 5: IF count1 == 3 THEN PRINT "Player 1 takes the cake"
ELSE PRINT "Player 2 takes the cake"
END
Python implementation
count1 = count2 = 0
while count1 < 3 and count2 < 3:
flip = int(input("Who won this flip (1 or 2)? "))
if flip == 1:
count1 += 1
else:
count2 += 1
if count1 == 3:
print("Player 1 takes the cake")
else:
print("Player 2 takes the cake")
Dry run for the input sequence 1, 2, 1, 1:
| Flip # | Input | count1 | count2 | Loop continues? |
|---|---|---|---|---|
| 1 | 1 | 1 | 0 | yes |
| 2 | 2 | 1 | 1 | yes |
| 3 | 1 | 2 | 1 | yes |
| 4 | 1 | 3 | 1 | no — count1 == 3 |
Output
Player 1 takes the cake
The loop condition count1 < 3 AND count2 < 3 is what makes the algorithm stop early — a fixed "repeat 5 times" loop would keep flipping after the contest is already decided.
Maintain count1/count2, increment the winner's counter each flip, and loop while both are below 3; whoever reaches 3 first takes the cake (e.g. input 1,2,1,1 → Player 1).
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.