Skip to content

Instantly share code, notes, and snippets.

@artemdemo
Created February 10, 2020 08:05
Show Gist options
  • Save artemdemo/f3e847cd752bc8f6f88c7f0cece8d00f to your computer and use it in GitHub Desktop.
Save artemdemo/f3e847cd752bc8f6f88c7f0cece8d00f to your computer and use it in GitHub Desktop.

Revisions

  1. artemdemo created this gist Feb 10, 2020.
    42 changes: 42 additions & 0 deletions game-of-life-v01.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    // 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();