Created
March 22, 2021 22:36
-
-
Save ryparker/8561fa075a67d292c0d285359808fcea to your computer and use it in GitHub Desktop.
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
// 1. Any live cell with fewer than two live neighbors dies, as if caused by under-population. | |
// 2. Any live cell with two or three live neighbors lives on to the next generation. | |
// 3. Any live cell with more than three live neighbors dies, as if by over-population.. | |
// 4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. | |
const input = [ | |
[0, 0, 1], | |
[0, 0, 0], | |
[0, 1, 1] | |
] | |
function applyCellRules(cellGroups){ | |
return cellGroups.map((cellGroup, cellGroupIdx) => { | |
return cellGroup.map((cell, cellIdx) => { | |
// Gather cell neighbors // | |
let neighborCellCount = 0 | |
// Get current row neighbors | |
neighborCellCount += countNeighborCells(cellGroup, cellIdx) | |
if (cellGroupIdx !== 0) { | |
// Get cells below | |
neighborCellCount += countNeighborCells( | |
cellGroups[cellGroupIdx - 1], | |
cellIdx | |
) | |
} | |
if (cellGroupIdx < cellGroups.length - 1) { | |
// Get cells above | |
neighborCellCount += countNeighborCells( | |
cellGroups[cellGroupIdx + 1], | |
cellIdx | |
) | |
} | |
return processCellRules(cell, neighborCellCount) | |
}) | |
}) | |
} | |
function countNeighborCells(cellGroup, cellIdx) { | |
// Get current cell position | |
let neighborCellCount = cellGroup[cellIdx] | |
if (cellIdx !== 0) { | |
// Get cell to left | |
neighborCellCount += cellGroup[cellIdx - 1] | |
} | |
if(cellIdx < cellGroup.length - 1){ | |
// Get cell to right | |
neighborCellCount += cellGroup[cellIdx + 1] | |
} | |
return neighborCellCount; | |
} | |
function processCellRules(originalCell, neighborCellCount) { | |
if (originalCell === 0) { | |
return applyDeadCellRules(neighborCellCount) | |
} | |
return applyLiveCellRules(neighborCellCount) | |
} | |
function applyLiveCellRules(neighborCellCount) { | |
if (neighborCellCount < 2) { | |
return 0 | |
} | |
if (2 <= neighborCellCount <= 3) { | |
return 1 | |
} | |
if (neighborCellCount > 3) { | |
return 0 | |
} | |
throw new Error(`No rules match neighborCellCount: ${neighborCellCount}`) | |
} | |
function applyDeadCellRules(neighborCount) { | |
if(neighborCount === 3){ | |
return 1; | |
} | |
return 0; | |
} | |
applyCellRules(input) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment