Game of Life

by Steven Senkus

JavaScript

/**

Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

Any live cell with fewer than two live neighbors dies, as if caused by under-population.
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies, as if by over-population..
Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

*/

/**
 * @param {number[][]} board
 * @return {void} Do not return anything, modify board in-place instead.
 */
var gameOfLife = function(board) {
  const DEAD = 0;
  const ALIVE = 1;

  const boardCopy = JSON.parse(JSON.stringify(board));
  
  // fix the x/y coordinates
  function findNumberOfLiveNeighbors(x, y) {
    let neighbors = 0
    
    function getValue(cx, cy, isCenter) {
        const cellRow = boardCopy[cy];
        if (!cellRow) return 'x';
          
        const cell = cellRow[cx];
        if (cell === DEAD) {
          return cell;
        } else if (cell === ALIVE) {
          if (!isCenter) neighbors++;
          return cell;
        } else {
          return 'x'
        }
    }
    
    //*
    console.log(`
${getValue(x-1,y-1)} ${getValue(x,y-1)} ${getValue(x+1,y-1)}
  
${getValue(x-1,y)} ${getValue(x,y, true)} ${getValue(x+1,y)}
  
${getValue(x-1,y+1)} ${getValue(x,y+1)} ${getValue(x+1,y+1)}
`)
    //*/
    return neighbors;

  }

  function cellBecomesAlive(y, x) {
    board[y][x] = 1;
    console.log('cell becomes alive');
  }

  function cellStaysAlive(y, x) {
      board[y][x] = 1;
      console.log('cell becomes alive');
  }

  function cellDies(y, x) {
      board[y][x] = 0;
      console.log('cell dies');
  }


  for (let y = 0; y < boardCopy.length; y++) {
    const currentRow = boardCopy[y];
    for (let x = 0; x < currentRow.length; x++) {
      let...