Game of Life
Turn a board of live and dead cells into its next generation in place, using a spare bit in each cell.
Conway's Game of Life is played on a board of cells, where each cell is live (1) or dead (0). The neighbours of a cell are the cells touching it: above, below, left, right and on the four diagonals, eight in all away from the edges. The next generation comes from two rules, applied to every cell at the same time:
- a live cell with 2 or 3 live neighbours stays alive, and any other live cell dies;
- a dead cell with exactly 3 live neighbours becomes alive, and any other dead cell stays dead.
Given the board as an int[][]
Example 1
Output: [[0, 0, 0], [1, 0, 1], [0, 1, 1], [0, 1, 0]]
Example 2
Output: [[1, 1], [1, 1]]
The Idea
The Game of Life is a tiny model of a population. A live cell needs some company to survive, but it dies when it is alone or crowded. A new cell appears on an empty spot where exactly three live cells meet. One step of the game turns the whole board into the next generation.
Take Example 1 and look at the cell in row 1, col 0. It is dead now. Around it are five cells on the board, and three of them are live: (row 0, col 1), (row 2, col 0) and (row 2, col 1). Exactly three, so it is born, and the output has a 1 there.
Now look at row 0, col 1. It is live, but its only live neighbour is row 1, col 2, so it dies. Here is the catch. Going row by row, this cell is handled first. If we write its 0 into the board straight away, row 1, col 0 later counts only two live neighbours and is never born.
So every cell has to keep its state now until all its neighbours have counted it, and also hold its state next somewhere. Where can both fit without a second board? Inside the cell itself. A Java int
Bits are counted from the right, starting at position 0. The board stores the state now in bit 0, and the state next can go into bit 1. The value 2, for example, is written 10
On the left, the dashed box holds row 1, col 0 and its neighbours, with the three live ones in blue. On the right, under "after the first pass", the same cell holds 1001
Solution Approach
The code has three jobs: count each cell's live neighbours, store the next states somewhere (first in a plain copy of the board, then in the spare bit), and make the next states the current ones.
Counting the neighbours
How do we visit the cells around row rcdrdc
The two rules then fold into one test. A cell lives next if it has exactly 3 live neighbours, whether it is live or dead now, or if it is live now and has exactly 2.
Keeping a copy of the board
What is the simplest place for the next states? A second int[][]
Two states in one cell
How do we read and write single bits? To read the state now, board[r][c] & 12 & 13 & 1
To mark a cell as live next, board[r][c] |= 2
Switching to the next generation
Once every cell has its bit 1, how does it become the state now? A second pass shifts every value one bit to the right with >>= 1
Java Solution
The method gameOfLife
- First, read the board's size into
androws .cols - Visit every cell with two loops, one inside the other: the outer loop moves
over the rows, and the inner loop movesr over the columns.c - For each cell, count its live neighbours into
. Two more loops runlive anddr from -1 to 1, giving the neighbour positiondc ,nr . The flagnc marks the cell itself; it is skipped, along with positions off the board, and every other neighbour addsself .board[nr][nc] & 1 - Read the cell's own state now into
. Ifalive is 3, orlive is true andalive is 2, set bit 1 withlive .board[r][c] |= 2 - After the first pass, a second pair of loops shifts every cell right by one bit with
.board[r][c] >>= 1
The main
public class GameOfLife {
// Bit 0 of a cell holds its state now, bit 1 its state in the next generation.
public static void gameOfLife(int[][] board) {
int rows = board.length;
int cols = board[0].length;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
int live = 0;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int nr = r + dr;
int nc = c + dc;
boolean self = dr == 0 && dc == 0;
if (!self && nr >= 0 && nr < rows && nc >= 0 && nc < cols) {
live += board[nr][nc] & 1; // read only the state now
}
}
}
boolean alive = (board[r][c] & 1) == 1;
if (live == 3 || (alive && live == 2)) {
board[r][c] |= 2; // lives in the next generation
}
}
}
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
board[r][c] >>= 1; // next state moves into bit 0
}
}
}
static void run(String name, int[][] board) {
System.out.println(name + ", before:");
print(board);
gameOfLife(board);
System.out.println("after:");
print(board);
System.out.println();
}
static void print(int[][] board) {
for (int[] row : board) {
System.out.println(" " + java.util.Arrays.toString(row));
}
}
public static void main(String[] args) {
run("Example 1", new int[][] {{0, 1, 0}, {0, 0, 1}, {1, 1, 1}, {0, 0, 0}});
run("Example 2", new int[][] {{1, 1}, {1, 0}});
run("A lone cell", new int[][] {{1}});
run("Three in a row", new int[][] {{0, 0, 0}, {1, 1, 1}, {0, 0, 0}});
}
}
Running it prints:
Example 1, before:
[0, 1, 0]
[0, 0, 1]
[1, 1, 1]
[0, 0, 0]
after:
[0, 0, 0]
[1, 0, 1]
[0, 1, 1]
[0, 1, 0]
Example 2, before:
[1, 1]
[1, 0]
after:
[1, 1]
[1, 1]
A lone cell, before:
[1]
after:
[0]
Three in a row, before:
[0, 0, 0]
[1, 1, 1]
[0, 0, 0]
after:
[0, 1, 0]
[0, 1, 0]
[0, 1, 0]
In Example 1, row 1 after the step reads [1, 0, 1]
The lone cell has no neighbours at all, so it dies and prints [0]
Reading only bit 0 is what keeps Example 1 right. A separate test program wrote each new state straight back as 0 or 1 in a single pass, and Example 1 came out as [[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 0, 0]]
Complexity
The board is read in two passes, and the first one looks at a fixed 3-by-3 square around each cell.
- Time: O(m × n) for a board of m rows and n columns, because the first pass checks at most 8 neighbours for each of the m × n cells and the second pass shifts each cell once.
- Space: O(1), because the next generation lives in bit 1 of each cell's own
, so no copy of the board is made.int
Another in-place matrix update where the order of writes needs care is