Skip to main content

Hard simulation · grids · self-organisation

Sandpile

Pour grains on one cell, let every tall stack topple, and a mandala appears.

Write sandpile(grains, size). Make a size by size grid of zeros (grid[y][x], y down, x right), put grains grains on the centre cell grid[Math.floor(size / 2)][Math.floor(size / 2)], then let it settle and return the settled grid.

Settling: any cell holding 4 or more grains topples. It loses 4 grains and gives 1 to each of its four neighbours (up, down, left, right). Grains pushed past the edge fall off and are gone. Keep toppling until every cell holds 0 to 3. The order you topple in does not change the final picture, so pick whatever is simplest.

Call show(grid) at least once while it settles, for example after each full sweep over the grid, and once more at the end.

Example: sandpile(4, 3) topples the centre once and returns [[0, 1, 0], [1, 0, 1], [0, 1, 0]].

Tests you can see

  • sandpile(4, 3)[[0,1,0],[1,0,1],[0,1,0]]
  • sandpile(16, 5)[[0,0,1,0,0],[0,2,1,2,0],[1,1,0,1,1],[0,2,1,2,0],[0,0,1,0,0]]
  • sandpile(300, 15)[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,1,2,3,3,3,2,1,0,0,0,0],[0,0,0,2,1,2,1,3,1,2,1,2,0,0,0],[0,0,2,2,3,1,3,3,3,1,3,2,2,0,0],[0,1,1,3,2,3,3,1,3,3,2,3,1,1,0],[0,2,2,1,3,2,2,0,2,2,3,1,2,2,0],[0,3,1,3,3,2,2,3,2,2,3,3,1,3,0],[0,3,3,3,1,0,3,0,3,0,1,3,3,3,0],[0,3,1,3,3,2,2,3,2,2,3,3,1,3,0],[0,2,2,1,3,2,2,0,2,2,3,1,2,2,0],[0,1,1,3,2,3,3,1,3,3,2,3,1,1,0],[0,0,2,2,3,1,3,3,3,1,3,2,2,0,0],[0,0,0,2,1,2,1,3,1,2,1,2,0,0,0],[0,0,0,0,1,2,3,3,3,2,1,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.

javascriptsandpile()

Tab indents · Cmd/Ctrl+Enter runs