Skip to main content

Hard cellular automata · simulation · grids

Langton's ant

Two rules, ten thousand steps of mess, then the ant builds a highway.

Write ant(width, height, steps). A grid of width by height cells starts all white (0), indexed grid[y][x] with y down and x right. The ant starts at x = Math.floor(width / 2), y = Math.floor(height / 2), facing up. Return the grid after the ant has taken steps steps.

Each step: on a white cell the ant turns 90 degrees right, on a black cell (1) it turns 90 degrees left. Then it flips the colour of the cell it is standing on and moves one cell forward. The world wraps: walking off one edge brings the ant back on the opposite edge.

Call show(frame) once before the first step and after every step. The frame is a copy of the grid with the ant's current cell set to 2, so the stage can draw the ant. The returned grid has no 2 in it.

Example: ant(3, 3, 2). The ant starts at (1, 1) facing up. Step 1: white, turn right to face right, flip (1, 1) to black, move to (2, 1). Step 2: white, turn right to face down, flip (2, 1), move to (2, 2). Result: [[0, 0, 0], [0, 1, 1], [0, 0, 0]].

Tests you can see

  • ant(3, 3, 2)[[0,0,0],[0,1,1],[0,0,0]]
  • ant(5, 5, 10)[[0,0,0,0,0],[0,1,1,0,0],[0,0,1,1,0],[0,0,1,1,0],[0,0,0,0,0]]
  • ant(21, 21, 400)[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,0,0],[0,0,0,0,0,1,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0],[0,0,0,0,1,1,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0],[0,0,0,0,1,0,1,1,1,1,1,1,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0],[0,0,0,0,0,0,1,1,0,0,0,1,0,0,1,0,0,0,0,0,0],[0,0,0,0,0,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,1,0,0,1,0,0,1,1,0,0,0,0,0,0],[0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,1,0,0,0,1,1,1,1,1,1,0,1,0,0,0,0],[0,0,0,0,0,1,0,1,1,0,0,0,0,0,1,1,1,0,0,0,0],[0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]

More tests are hidden. The server runs them all before a time counts.

Call show() while your code works and the run plays back here.

javascriptant()

Tab indents · Cmd/Ctrl+Enter runs