Created
February 10, 2020 08:05
-
-
Save artemdemo/f3e847cd752bc8f6f88c7f0cece8d00f to your computer and use it in GitHub Desktop.
Game of life - v.01
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
// 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