Created
February 10, 2020 08:05
-
-
Save artemdemo/903521acde48981df950e73728429f22 to your computer and use it in GitHub Desktop.
Game of life - v.02
This file contains 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 populate = (matrix) => { | |
return matrix.map(row => row.map(_ => Math.random() >= 0.5)); | |
}; | |
const createMatrix = (width, height) => { | |
const matrix = Array.from(new Array(height)).map(_ => Array.from(new Array(width))); | |
return populate(matrix); | |
}; | |
const printMatrix = (matrix) => { | |
matrix.forEach((row) => { | |
console.log(row.map(item => item ? '*' : 'o').join(' ')); | |
}); | |
}; | |
const isNeighbour = (rowIdx, colIdx, i, j) => { | |
return (i <= rowIdx + 1 && i >= rowIdx - 1) && | |
(j <= colIdx + 1 && j >= colIdx - 1) && | |
(!(i === rowIdx && j === colIdx)); | |
}; | |
const getLiveNeighboursCount = (matrix, rowIdx, colIdx) => { | |
return matrix.reduce((acc, row, i) => { | |
return acc + row.filter((_, j) => isNeighbour(rowIdx, colIdx, i, j)) | |
.reduce((rowAcc, item) => rowAcc + (item ? 1 : 0), 0); | |
}, 0); | |
}; | |
const apply = matrix => matrix.map((row, i) => row.map((item, j) => { | |
const count = getLiveNeighboursCount(matrix, i, j); | |
return count === 3 || (item && count === 2); | |
})); | |
const main = () => { | |
const matrix = createMatrix(4, 4); | |
printMatrix(matrix); | |
console.log(); | |
printMatrix(apply(matrix)); | |
}; | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment