// 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();