docs

#Game of Life

On this page

Run Conway's Game of Life on a 10×8 torus grid whose edges wrap around, printing a few generations as text.

#Code

#Walkthrough

  • The grid is a fixed-size 2D array [[bool; W]; H] (10×8). Arrays carry their size in the type and need no separate allocation; they are built with the repeat form [[false; W]; H] and compared whole with == / != (Values and types).
  • Neighbors are counted with (x + W - 1) % W instead of x - 1. This avoids usize subtraction going below zero and makes the edges wrap to the opposite side.
  • The survival rule is a single match on the (alive, neighbors) tuple. Patterns can be combined with |, as in (true, 2) | (true, 3) (3.12 match, Control flow).
  • impl Display for Grid writes one character at a time with Formatter::write_char, so f"{grid}" draws the grid (Formatter, Structs, enums and traits).
  • A glider moves one cell diagonally every 4 generations, keeping its shape. On a 10×8 torus it needs lcm(10, 8) = 40 moves to return to its starting place, which takes 160 generations.

Found a mistake? Edit this page on GitHub. Last updated