Created
February 12, 2019 19:09
-
-
Save danielrobertson/b1a384e2dc7f7b94eb53d2a213b56e1b to your computer and use it in GitHub Desktop.
Conway's game of life
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Input: | |
an n by m grid of "alive" or "dead" cells | |
Output: | |
a transformation on the input grid using the following rules: | |
- An "alive" cell remains alive if 2 or 3 neighbors are "alive." Otherwise, it becomes "dead." | |
- A "dead" cell becomes alive if exactly 3 neighbors are "alive." Otherwise, it remains "dead." | |
(The term "neighbor" refers to the at-most-8 adjacent cells horizontally, vertically, and diagonally.) | |
Input: | |
x x - - x x | |
x - - - x x | |
- - - x - - | |
Output: | |
x x - - x x | |
x x - x - x | |
- - - - x - | |
(0,0) (0,1) (0,2) | |
(1,0) (1,1) (1,2) | |
(2,0) (2,1) (2,2) | |
*/ | |
// assumption: non-jaged grid | |
function generateNextPhase(grid) { | |
// initialize blank grid | |
let newGrid = []; // [[],[],[]] | |
//iterate each row and column | |
for(let i = 0; i < grid.length; i++) { | |
for(let j = 0; j < grid[i]; j++) { | |
const val = grid[i][j]; | |
// check all 8 neighbors and update | |
newGrid[i][j] = computeNewValue(grid, i, j); | |
} | |
} | |
return newGrid; | |
} | |
// accepts a 2d grid and x,y coordinates | |
// returns the new value for the x,y coordinate | |
function computeNewValue(grid, x, y) { | |
let newVal = ""; | |
// checking all 8 neighbors, respect out of bounds | |
let aliveNeighbors = 0; | |
// loop to somehow run this box around x,y | |
for(let i = x - 1; i <= x + 1 ; i++) { | |
for(let j = y - 1; j <= y + 1; j++) { | |
// bounds checking | |
if(!((i === x && j === y) || i < 0 || j < 0 || i > grid.length - 1 || j > grid[i].length - 1)) { | |
const val = grid[i][j]; | |
if(val === 'x') { | |
++aliveNeighbors; | |
} | |
} | |
} | |
} | |
// applying rules | |
const originalVal = grid[x][y]; | |
if(originalVal === 'x') { | |
newVal = (aliveNeighbors === 2 || aliveNeighbors === 3) ? 'x' : '-'; | |
} else if(originalVal === '-') { | |
newVal = aliveNeighbors === 3 ? 'x' : '-'; | |
} | |
// TODO clean up with ternary operator ? : | |
return newVal; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment