
Think it through · Start with a story
A game piece starts at 0, moves two steps right, then one step left. The robot records its position after every move.
Break Down the Process
- Start0
- Move right by 2Now at 2
- Move left by 1Now at 1
- FinishAt 1
Simulation updates a state according to the rules given in a problem.
A state is the information we need to keep track of at a particular moment, such as position, direction, or remaining turns. After each action, continue with the updated state.
01What Is Simulation?
Simulation means making a program follow the rules in a problem, one step at a time.
For example, move a game piece two spaces to the right each turn, for five turns:
int position = 0;
for (int step = 0; step < 5; step++) {
position += 2;
}
02What Matters Most in a Simulation?
It is not how much code you write; it is translating the rules accurately.
State
Which values can change?
Rules
How does each step change them?
Order
What happens first and next?
Stopping point
When does the process end?
03What Is a “State”?
A state is the data needed to describe the problem at a particular moment.
A small game might need to track:
- The character’s position
- Health points
- Current score
- Time remaining
04Why Can the Order of Operations Go Wrong?
Suppose the rule says, “Move first, then check whether you hit a wall.” If the program checks first and moves afterward, the result may be different.
05Why Do Simulation Problems Have Boundary Bugs?
Rules often include special cases such as “the first round,” “the last square,” or “return to the beginning after passing the limit.”
06How Can You Debug a Simulation?
One of the most effective methods is to print or make a table of the state after each step:
| Step | Position | Score |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 2 | 10 |
| 2 | 4 | 20 |
What You Have Learned
- Simulation translates rules into a program and follows them in order.
- Clearly define the state, rules, and stopping condition first.
- The order of operations can directly change the result.
- Check boundaries and special cases carefully in simulation problems.
- Recording each state step by step is a useful debugging method.
Next: Linear Search: Look from Beginning to End
Your Turn to Try
If the program incorrectly starts the move left by 1 from the original position in step two, what wrong position will it get?
Have you decided? Open to see the explanation
It will get −1. The correct move starts from the updated position 2, so the answer is 1.