Arrays & Hashing · Pattern 19 of 26

Simulation: do exactly what the problem says

No trick, just careful bookkeeping. Represent the state cleanly (direction vectors, an index into the input), handle every edge case the statement mentions, and test on the examples.

4 variations · 13 problems · 1 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • A robot, a grid or a game that follows step-by-step rules
  • Parse a string into a number, an IP address or code
  • Format text into lines, words or a pattern

The template

Simulation
// a robot on a grid: directions as vectors, turning changes the index
boolean isRobotBounded(String instructions) {
    int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};   // north, east, south, west
    int x = 0, y = 0, d = 0;
    for (char c : instructions.toCharArray()) {
        if (c == 'G') { x += dirs[d][0]; y += dirs[d][1]; }
        else if (c == 'R') d = (d + 1) % 4;
        else d = (d + 3) % 4;                             // L
    }
    return (x == 0 && y == 0) || d != 0;   // back home, or facing a new way: it loops
}

The variations

  1. 1Directions and grids

    Keep the direction as an index into a vector array; turning is ± 1 mod 4. Repeat gravity or crushing until nothing changes.

  2. 2Parse carefully

    Walk the string with an index: skip spaces, read the sign, read digits, stop early on overflow. Split on separators and validate each part.

  3. 3Build the output line by line

    Decide what goes on each line or row, then format it. Zigzag is "which row does character i go to"; text justification spreads spaces left first.

  4. 4More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Writing four copies of the same move code instead of one direction array.
  • Skipping edge cases the statement lists: leading spaces, signs, overflow, empty lines.
  • Not re-reading the statement after coding; simulations fail on details.
Next: The contribution technique →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.