Game of Life

Conway's Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input.

Rules

Given a 2D matrix, in which each cell represents the population in that locality

Consider the following:

  • Any live cell with fewer than two live neighbours dies, as if by underpopulation.
  • Any live cell with two or three live neighbours lives on to the next generation.
  • Any live cell with more than three live neighbours dies, as if by overpopulation.
  • Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
  • Change the population of the cell by clicking on it.
    Then click on play to run the game of life.

    The game of life runs by itself. You can pause or resume it.

    Solution

    function deepCopyGrid(pile) { const newPile = []; for (const pileRow of pile) { newPile.push([...pileRow]); } return newPile; } function isValid(i, j, r, c) { return i >= 0 && i < r && j >= 0 && j < c; } function countLiveNeighbours(pile, i, j) { let n = 0 - pile[i][j]; for (let p = i - 1; p <= i + 1; p++) { for (let q = j - 1; q <= j + 1; q++) { if (isValid(p, q, pile.length, pile[0].length)) { n += pile[p][q]; } } } return n; } function nextIteration(pile) { let newPile = deepCopyGrid(pile); for (let i = 0; i < pile.length; i++) { for (let j = 0; j < pile[0].length; j++) { let n = countLiveNeighbours(pile, i, j); if (n == 3) { newPile[i][j] = 1; } else if (n < 2 || n > 3) { newPile[i][j] = 0; } } } return newPile; }
    Home | © 2024 Last Updated: Mar 03, 2024
    Buy Me A Coffee