Game of Life

Conway’s Game of Life, cellular automaton operates on a two-dimensional grid of cells, where each cell can be in one of two states:
Alive (1)
Dead (0)

Here are the rules:
A live cell with fewer than 2 live neighbors dies (underpopulation).
A live cell with 2 or 3 live neighbors stays alive (survival).
A live cell with more than 3 live neighbors dies (overpopulation).
A dead cell with exactly 3 live neighbors becomes alive (reproduction).

The grid should be updated only after evaluating the whole grid first.

const rows = 3
const cols = 3

const grid = [
  [0, 1, 0],
  [0, 1, 0],
  [0, 1, 0]
]

const nextGrid = Array.from({ length: rows }, () => Array(cols).fill(0))

for (let i = 0; i < rows; i++) {
  for (let j = 0; j < cols; j++) {
    const neighbors = countNeighbors(grid, i, j, rows, cols)

    console.log("count neigbor is", neighbors)

    const cell = grid[i][j]

    if (cell === 1) {
      if (neighbors < 2) {
        // die
        nextGrid[i][j] = 0
      } else if (neighbors === 2 || neighbors === 3) {
        // live
        nextGrid[i][j] = 1
      } else if (neighbors > 3) {
        // die
        nextGrid[i][j] = 0
      }
    } else {
      if (neighbors === 3) {
        nextGrid[i][j] = 1
      }
    }
  }
}

console.log("grid is", grid)
console.log("nextGrid is", nextGrid)

function countNeighbors(grid, row, col, rows, cols) {
  const rowAbove = row - 1
  const rowBelow = row + 1
  const colLeft = col - 1
  const colRight = col + 1

  const neighbors = [
    [rowAbove, colLeft],
    [rowAbove, col],
    [rowAbove, colRight],
    [row, colLeft],
    [row, colRight],
    [rowBelow, colLeft],
    [rowBelow, col],
    [rowBelow, colRight]
  ]

  let count = 0

  for (let neighbor of neighbors) {
    const [r, c] = neighbor

    if (r >= 0 && r <= rows - 1 && c >= 0 && c <= cols - 1) {
      if (grid[r][c]) count++
    }

  return count
}

Output is

grid is [ [ 0, 1, 0 ], [ 0, 1, 0 ], [ 0, 1, 0 ] ]
nextGrid is [ [ 0, 0, 0 ], [ 1, 1, 1 ], [ 0, 0, 0 ] ]
Scroll to top