Skip to content

Instantly share code, notes, and snippets.

@artemdemo
Created February 10, 2020 08:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artemdemo/f3e847cd752bc8f6f88c7f0cece8d00f to your computer and use it in GitHub Desktop.
Save artemdemo/f3e847cd752bc8f6f88c7f0cece8d00f to your computer and use it in GitHub Desktop.
Game of life - v.01
// https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
const generateMatrix = (width, height) => {
return Array.from({length: height}, () => Array.from({length: width}, () => Math.random() >= 0.5));
};
const nextCellState = (matrix, rowIdx, colIdx) => {
const numberOfLiveNeighbors = [
[-1, -1], [-1, 0], [-1, 1],
[ 0, -1], [ 0, 1],
[ 1, -1], [ 1, 0], [ 1, 1],
].map((indexesDiff) => {
const neighborRowIdx = rowIdx + indexesDiff[0];
const neighborColIdx = colIdx + indexesDiff[1];
return (neighborRowIdx < 0 || neighborColIdx < 0 || neighborRowIdx >= matrix.length || neighborColIdx >= matrix[0].length)
? 0
: Number(matrix[neighborRowIdx][neighborColIdx])
}).reduce((acc, item) => {
return acc + item;
}, 0);
return numberOfLiveNeighbors === 3 || (matrix[rowIdx][colIdx] && numberOfLiveNeighbors === 2);
};
const applyStep = (matrix) => {
return matrix.map((row, rowIdx) => row.map((col, colIdx) => nextCellState(matrix, rowIdx, colIdx)));
};
const printMatrix = (matrix) => {
matrix.forEach((row) => {
console.log(row.map(item => item ? '*' : 'o').join(' '));
});
};
const main = () => {
const matrix = generateMatrix(4, 4);
printMatrix(matrix);
console.log();
printMatrix(applyStep(matrix));
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment