Builds onArrays and strings
01The idea
Some problems have no clever trick. They describe a process step by step, and the answer is whatever the process produces. Your job is to carry out the rules exactly, with clean state and no mistakes.
Simulation code is easier to get right when the state is small and clear:
- Keep the smallest state that describes the moment: a position, a direction, a counter, a grid.
- Store directions in a list, in clockwise order. Then a right turn is
(d + 1) % 4and a left turn is(d + 3) % 4. A single list of moves replaces fourifbranches. - When every cell of a grid changes at once, compute the new grid from the old one. Do not overwrite cells you still need to read.
- Write each rule from the problem as one small piece of code, in the order the problem gives.
Before you simulate, check the size. If the process runs a billion steps, a step-by-step loop is too slow. Look for a cycle. After some steps the state repeats, and you can skip whole rounds with division and a remainder.
02How to spot it
The problem is a simulation when:
- it describes moves, turns, rounds or ticks, and asks for the final state
- it says "repeat until" and the number of steps is small
- it walks a grid in a fixed pattern, such as a spiral or a zigzag
- it models a game, a queue of people, or a machine with a few rules
The signal is a problem statement that is long and precise about each step, with no hint of searching or optimizing. Read it twice and list the rules before you write code.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue