Created
August 11, 2020 23:25
-
-
Save nimamehanian/4886ad3472bcd5575d1280b6b2c7a153 to your computer and use it in GitHub Desktop.
Conway Game Of Life
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
const gen0 = [ | |
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 1, 1, 0, 0], | |
[0, 0, 0, 1, 0, 0, 1, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], | |
]; | |
// CONWAY GAME OF LIFE — CONSTRAINTS: | |
// Any live cell with 0 or 1 live neighbors dies by underpopulation. | |
// Any live cell with 2 or 3 live neighbors stays alive. | |
// Any live cell with 4 or more live neighbors dies by smothering. | |
// Any dead cell with exactly 3 live neighbors becomes a live cell, as if revitalized. | |
const getNumberOfNeighbors = ({ | |
c, | |
x, | |
y, | |
isNotAtTopPerimeter, | |
isNotAtRightPerimeter, | |
isNotAtBottomPerimeter, | |
isNotAtLeftPerimeter, | |
}) => ([ | |
(() => isNotAtTopPerimeter && isNotAtLeftPerimeter ? c[y - 1][x - 1] : 0)(), // topLeft | |
(() => isNotAtTopPerimeter ? c[y - 1][x] : 0)(), // top | |
(() => isNotAtTopPerimeter && isNotAtRightPerimeter ? c[y - 1][x + 1] : 0)(), // topRight | |
(() => isNotAtLeftPerimeter ? c[y][x - 1] : 0)(), // left | |
(() => isNotAtRightPerimeter ? c[y][x + 1] : 0)(), // right | |
(() => isNotAtBottomPerimeter && isNotAtLeftPerimeter ? c[y + 1][x - 1] : 0)(), // bottomLeft | |
(() => isNotAtBottomPerimeter ? c[y + 1][x] : 0)(), // bottom | |
(() => isNotAtBottomPerimeter && isNotAtRightPerimeter ? c[y + 1][x + 1] : 0)(), // bottomRight | |
].filter(Boolean).length); | |
const elapseOneGeneration = culture => ( | |
culture.reduce((nextGen, group, y) => ([ | |
...nextGen.slice(0, y), | |
group.map((cell, x) => { | |
const isCellAlive = !!cell; | |
const numberOfNeighbors = getNumberOfNeighbors({ | |
c: nextGen, | |
x, | |
y, | |
isNotAtTopPerimeter: y > 0, | |
isNotAtRightPerimeter: x < group.length - 1, | |
isNotAtBottomPerimeter: y < culture.length - 1, | |
isNotAtLeftPerimeter: x > 0, | |
}); | |
return isCellAlive ? | |
(numberOfNeighbors > 1 && numberOfNeighbors < 4 ? 1 : 0) : | |
(numberOfNeighbors === 3 ? 1 : 0); | |
}), | |
...nextGen.slice(y + 1), | |
]), culture) | |
); | |
const gen1 = elapseOneGeneration(gen0); | |
console.log(gen1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment