Skip to main content

Medium cellular automata · bits · simulation

Rule 30 and friends

Eight bits of a rule number grow a whole world, one row at a time.

Write automaton(rule, width, steps). It runs an elementary cellular automaton and returns steps + 1 rows, each an array of width cells that are 0 or 1.

Row 0 is all 0 except a single 1 at index Math.floor(width / 2). Each next row comes from the one above: for cell i, read left = above[i - 1], centre = above[i] and right = above[i + 1], treating anything past either edge as 0. The pattern number is left * 4 + centre * 2 + right, from 0 to 7, and the new cell is (rule >> pattern) & 1.

Call show(rows) after each row is added (including row 0) so the triangle grows downward on the stage.

Example: automaton(90, 5, 2) returns [[0, 0, 1, 0, 0], [0, 1, 0, 1, 0], [1, 0, 0, 0, 1]]. Rule 90 makes each cell the XOR of its two neighbours, which draws Sierpinski's triangle. Rule 30 draws chaos.

Tests you can see

  • automaton(90, 5, 2)[[0,0,1,0,0],[0,1,0,1,0],[1,0,0,0,1]]
  • automaton(30, 9, 4)[[0,0,0,0,1,0,0,0,0],[0,0,0,1,1,1,0,0,0],[0,0,1,1,0,0,1,0,0],[0,1,1,0,1,1,1,1,0],[1,1,0,0,1,0,0,0,1]]
  • automaton(90, 31, 15)[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,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,1,0,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,1,0,0,0,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,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],[0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0],[0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0],[0,0,0,0,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,1,0,0,0,0],[0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0],[0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0],[0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0],[1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1]]

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.

javascriptautomaton()

Tab indents · Cmd/Ctrl+Enter runs