Skip to content

Instantly share code, notes, and snippets.

@GBurgardt
Created July 14, 2017 19:27
Show Gist options
  • Save GBurgardt/28509bf9c29c6f774ffa71dd8fa1cfcd to your computer and use it in GitHub Desktop.
Save GBurgardt/28509bf9c29c6f774ffa71dd8fa1cfcd to your computer and use it in GitHub Desktop.
Game of life [iSeatz] (Germán Burgardt)
const getLivingNeighbors = (board, xCell, yCell) => {
let livingNeighbors = 0;
for (let row = -1; row <= 1; row++){
for (let column = -1; column <= 1; column++) {
if (row === 0 && column === 0) {
continue;
}
if((board[yCell + column]) && (board[yCell + column][xCell + row])
&& (board[yCell + column][xCell + row] === 1)) {
livingNeighbors++;
}
}
}
return livingNeighbors;
};
const nextGeneration = board => {
let nextBoard = board.map((row, yCell) => {
return nextRow = row.map((cell, xCell) => {
let newCellLife = cell;
let livingNeighbors = getLivingNeighbors(board, xCell, yCell);
if (cell === 1) {
if (livingNeighbors < 2 || livingNeighbors > 3) {
newCellLife = 0
}
} else {
if (livingNeighbors === 3) {
newCellLife = 1
}
}
return newCellLife;
})
});
return nextBoard;
};
nextGeneration([
[1, 1, 1],
[1, 0, 0],
[1, 1, 0]
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment