Cannonball is a direct simulation problem. These problems are not about a clever formula. They are about maintaining state carefully and applying the rules in the correct order.
Name the state variables
A good simulation begins by naming exactly what changes over time:
position: where the cannonball is now.power: how far it moves each jump.direction: left or right.broken: which targets have already been broken.
If a variable cannot be explained in one sentence, debugging becomes much harder.
The simulation loop
Each iteration moves the cannonball, checks whether it is outside the field, and then applies the rule for the landing position.
while true:
position = position + direction * power
if position is outside:
stop
if spot is a target:
break it if power is enough
else if spot is a booster:
increase power
reverse direction
Why order matters
Changing direction before increasing power, or counting a broken target twice, can change the answer. Simulation problems reward careful sequencing.
Common mistakes
- Using 0-indexing in arrays after reading 1-indexed positions without converting carefully.
- Breaking the same target more than once.
- Forgetting to stop when the position leaves the valid range.
- Applying the bounce rule to target cells or the target rule to bounce cells.
Practice prompt
Make a five-position field with one booster and two targets. Start at position 2 with power 1. Trace position, power, direction, and broken target count after every jump.
