Skip to lesson

Simulation problems

Not every coding problem requires a clever mathematical shortcut — many ask you to simulate a set of rules step by step (moving a robot on a grid, dealing cards, or evolving cells in Conway's Game of Life). The secret to simulation problems is organising your state so the code stays short and bug-free.

Following rules step by step and keeping state in variables

A simulation solves a problem by following its rules step by step in code, exactly as the story describes, instead of using a formula.

A simulation problem gives a starting state and rules, and asks for the final state. Keep the state in a few variables and use direction arrays for moves. The code below moves a robot.

For example, suppose a robot starts at (x = 0, y = 0) facing North and executes commands 'G' (go forward 1 unit), 'L' (turn 90 degrees left), and 'R' (turn 90 degrees right). Instead of writing four if branches for North, East, South, and West on every 'G', store the four directions in clockwise order (0 = North, 1 = East, 2 = South, 3 = West):

  • int[] dx = {0, 1, 0, -1};
  • int[] dy = {1, 0, -1, 0};

Example 1 · Simulating a grid robot with direction vectors (dx, dy) and modulo turns

RobotSimulationDemo.javaJava
public class RobotSimulationDemo {    static String simulateRobot(String commands) {        // 0 = North, 1 = East, 2 = South, 3 = West        int[] dx = {0, 1, 0, -1};        int[] dy = {1, 0, -1, 0};        String[] dirNames = {"North", "East", "South", "West"};
        int x = 0, y = 0, dir = 0;        for (int i = 0; i < commands.length(); i++) {            char cmd = commands.charAt(i);            if (cmd == 'R') {                dir = (dir + 1) % 4;            } else if (cmd == 'L') {                dir = (dir + 3) % 4;            } else if (cmd == 'G') {                x += dx[dir];                y += dy[dir];            }        }        return "pos=(" + x + ", " + y + "), facing=" + dirNames[dir];    }
    public static void main(String[] args) {        System.out.println("GGRGGG  -> " + simulateRobot("GGRGGG"));        System.out.println("GLGLGLG -> " + simulateRobot("GLGLGLG"));    }}
Output
GGRGGG  -> pos=(3, 2), facing=East
GLGLGLG -> pos=(0, 0), facing=East

What this code does

  • On "GGRGGG", the robot walks 2 steps North to (0, 2), turns Right to face East (dir = 1), and walks 3 steps East to (3, 2).
  • On "GLGLGLG", the robot traces all four sides of a 1 × 1 square (North -> West -> South -> East) and returns to (0, 0) facing East.

A simulation problem gives you an initial state and a list of transition rules or commands, and asks for the final state after running the process. Instead of writing giant nested if-else trees, represent the system's state in a few clear variables and use direction arrays for movement.

Now turning right is just dir = (dir + 1) % 4, turning left is dir = (dir + 3) % 4, and moving forward is x += dx[dir]; y += dy[dir];!

  • Direction arrays (dx, dy or dr, dc): replace 4-branch switch statements with 1-line index arithmetic.
  • Right turn: dir = (dir + 1) % 4 (clockwise).
  • Left turn: dir = (dir + 3) % 4 (avoids negative remainder -1 % 4 in Java).
  • Helper methods: extract one helper per rule (e.g., countLiveNeighbours(grid, r, c)) so the main loop reads like plain English.

Game-of-Life style grids: simultaneous state transitions

In Conway's Game of Life every cell updates at the same moment, so you must not overwrite a cell before its neighbours have read it. The code below shows the safe way.

The classic simulation bug: If you overwrite board[r][c] directly while looping through the grid, then when you reach board[r][c + 1], its left neighbour board[r][c] already holds the next generation's value instead of the current generation's value!

Example 2 · Simulating Conway's Game of Life (the Blinker oscillator) without state corruption

GameOfLifeDemo.javaJava
import java.util.Arrays;
public class GameOfLifeDemo {    static int countLiveNeighbours(int[][] board, int r, int c) {        int rows = board.length, cols = board[0].length;        int live = 0;        for (int dr = -1; dr <= 1; dr++) {            for (int dc = -1; dc <= 1; dc++) {                if (dr == 0 && dc == 0) continue;                int nr = r + dr, nc = c + dc;                if (nr >= 0 && nr < rows && nc >= 0 && nc < cols) {                    live += board[nr][nc];                }            }        }        return live;    }
    static int[][] nextGeneration(int[][] board) {        int rows = board.length, cols = board[0].length;        int[][] next = new int[rows][cols];        for (int r = 0; r < rows; r++) {            for (int c = 0; c < cols; c++) {                int live = countLiveNeighbours(board, r, c);                if (board[r][c] == 1) {                    next[r][c] = (live == 2 || live == 3) ? 1 : 0;                } else {                    next[r][c] = (live == 3) ? 1 : 0;                }            }        }        return next;    }
    static void printBoard(String title, int[][] board) {        System.out.println(title);        for (int[] row : board) {            System.out.println("  " + Arrays.toString(row));        }    }
    public static void main(String[] args) {        int[][] blinker = {            {0, 0, 0},            {1, 1, 1},            {0, 0, 0}        };        printBoard("Gen 0 (horizontal):", blinker);        int[][] gen1 = nextGeneration(blinker);        printBoard("Gen 1 (vertical):", gen1);        int[][] gen2 = nextGeneration(gen1);        printBoard("Gen 2 (back to horizontal):", gen2);    }}
Output
Gen 0 (horizontal):
  [0, 0, 0]
  [1, 1, 1]
  [0, 0, 0]
Gen 1 (vertical):
  [0, 1, 0]
  [0, 1, 0]
  [0, 1, 0]
Gen 2 (back to horizontal):
  [0, 0, 0]
  [1, 1, 1]
  [0, 0, 0]

What this code does

  • Reading from board while writing into next ensures all 9 cells see the exact Generation 0 state.
  • The horizontal blinker [1, 1, 1] becomes a vertical column in Generation 1 and returns to horizontal in Generation 2, confirming our 8-neighbour counting and birth/survival rules.

Example 3 · In-place Game of Life using 2-bit state encoding (O(1) extra space)

InPlaceGameOfLifeDemo.javaJava
import java.util.Arrays;
public class InPlaceGameOfLifeDemo {    static void stepInPlace(int[][] board) {        int rows = board.length, cols = board[0].length;        for (int r = 0; r < rows; r++) {            for (int c = 0; c < cols; c++) {                int live = 0;                for (int dr = -1; dr <= 1; dr++) {                    for (int dc = -1; dc <= 1; dc++) {                        if (dr == 0 && dc == 0) continue;                        int nr = r + dr, nc = c + dc;                        if (nr >= 0 && nr < rows && nc >= 0 && nc < cols) {                            live += (board[nr][nc] & 1); // Bit 0 holds old state!                        }                    }                }                int oldState = board[r][c] & 1;                int nextState = (oldState == 1) ? ((live == 2 || live == 3) ? 1 : 0)                                                : ((live == 3) ? 1 : 0);                board[r][c] |= (nextState << 1); // Store next state in bit 1!            }        }        for (int r = 0; r < rows; r++) {            for (int c = 0; c < cols; c++) {                board[r][c] >>= 1; // Promote bit 1 to bit 0            }        }    }
    public static void main(String[] args) {        int[][] board = {{0, 1, 0}, {0, 1, 0}, {0, 1, 0}};        stepInPlace(board);        for (int[] row : board) {            System.out.println(Arrays.toString(row));        }    }}
Output
[0, 0, 0]
[1, 1, 1]
[0, 0, 0]

What this code does

  • Because each cell is originally 0 or 1, bit 0 (board[nr][nc] & 1) preserves the old state while bit 1 (nextState << 1) records the new state.
  • A second pass shifts every cell right by 1 bit (>>= 1), completing the simultaneous update in O(1) extra space.

In Conway's Game of Life (and many grid-infection, rotting-oranges, or cellular-automaton problems), every cell (r, c) updates to its next generation simultaneously based on its 8 neighbours (dr in -1..1, dc in -1..1, excluding (0, 0)):

  • A live cell (1) with < 2 or > 3 live neighbours dies (0); with 2 or 3 live neighbours it survives (1).
  • A dead cell (0) with exactly 3 live neighbours becomes alive (1).

You have two clean ways to perform simultaneous updates:

  1. Two-grid approach (O(R × C) extra space): Read neighbour counts exclusively from board and write new values into int[][] next = new int[R][C]. Simple, clear, and impossible to corrupt.
  2. In-place 2-bit encoding (O(1) extra space): Store the old state in bit 0 (board[r][c] & 1) and write the new state into bit 1 (board[r][c] |= 2), then shift every cell right by 1 bit (board[r][c] >>= 1) in a second pass.
  3. Write a helper countNeighbours(int[][] grid, int r, int c) that checks all 8 offsets (dr, dc) inside bounds 0 <= nr < R and 0 <= nc < C.
  4. Never overwrite a cell's old state while other cells still need to read that old state.
  5. Either write to a fresh next[R][C] array or encode (oldState, newState) in two bits (0..3).

Testing a simulation step by step

Because a simulation chains many steps together, a tiny mistake on step 1 cascades into a completely wrong answer by step 50. To test a simulation effectively:

  1. Print intermediate states after 1 step: Verify a single tick or single command by hand before running 100 steps.
  2. Test known invariants or periodic patterns: For example, in Game of Life, a 2 × 2 block of 1s is a still life (never changes), and a horizontal bar of three 1s ([1, 1, 1], the blinker) flips to a vertical bar of three 1s on step 1 and flips right back on step 2!
Testing a known 2-step oscillator like the Game of Life 'blinker' (horizontal -> vertical -> horizontal) immediately verifies all 8 neighbour offsets and both birth/death rules.

Next step

Check your understanding

10 quick questions