Task 1 of 5

The Neighbor Census

A cellular automaton is a world of cells, each one dead (0) or alive (1), where every cell's next state depends only on its immediate neighborhood. That makes it embarrassingly parallel: 256 cells, 256 threads, and no thread needs to know what any other thread is doing — only what the grid looked like.

Every rule in this module starts with the same question: how many of my eight neighbors are alive? This world is a torus — walk off the right edge, reappear on the left — and wrapping costs one modulo: (x + dx + 16) % 16. The + 16 is not decoration: JavaScript's % can go negative while the GPU's cannot, and adding the width first keeps both operands positive so CPU mode and GPU mode tell the same story.

sum the 3×3 block, subtract yourself — and the torus has no edges
Goal: make the kernel return, for every cell, the number of live cells among its eight neighbors — with the edges wrapped around.

Requirements

Hint 1 — the loop bounds

Two statically bounded loops: for (let dy = -1; dy < 2; dy++) around for (let dx = -1; dx < 2; dx++). Nine visits per cell.

Hint 2 — the subtract-self trick

Skipping the middle of the 3×3 block needs no if: sum all nine cells, then subtract grid[this.thread.y][this.thread.x] at the end. If you're dead you subtract 0; if you're alive you take yourself back out.

Hint 3 — the whole loop body
const yy = (this.thread.y + dy + 16) % 16;
const xx = (this.thread.x + dx + 16) % 16;
count += grid[yy][xx];

— then

return count - grid[this.thread.y][this.thread.x];

Same idea elsewhere

Reading a fixed window around your own coordinate is the stencil pattern, and it dominates real GPU workloads: CUDA stencil kernels tile the grid into shared memory with a one-cell "halo" so neighbors are read once, and WebGPU compute shaders do the same with workgroup memory.

All tasks in Cellular Automata

  1. The Neighbor Census
  2. One Tick of Life
  3. Generations: Feed It Back
  4. Watch the Glider Fly
  5. One Kernel, Every Universe

This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.