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/903521acde48981df950e73728429f22 to your computer and use it in GitHub Desktop.
Save artemdemo/903521acde48981df950e73728429f22 to your computer and use it in GitHub Desktop.
Game of life - v.02
// 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