Last active
August 15, 2022 10:48
-
-
Save kissarat/2c1a04483889c4a3e7042a4d48f333ee 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
const equals = (a, b) = a[0] == b[0] && a[1] === b[1] | |
const zone = [-1, 0, 1] | |
function *around([x, y]) { | |
for (const i of zone) { | |
for (const j of zone) { | |
if (0 === i && 0 === y) { | |
continue | |
} | |
yield [x + i, y + j] | |
} | |
} | |
} | |
const near = (cell, neighbor) => 1 === Math.abs(neighbor[0] - cell[0]) | |
|| 1 === Math.abs(neighbor[1] - cell[1]) | |
const willLive = (n) => 2 == n || 3 == n | |
const inSet = (cell, cells) => cells.find(item => equals(cell, item)) | |
function next(cells) { | |
const newCells = [] | |
for(let cell of cells) { | |
for(const neighbor of around(cell)) { | |
if (inSet(neighbor, cells) || inSet(neighbor, newCells)) { | |
continue | |
} | |
let n = 0 | |
for (const item of cells) { | |
if (near(neighbor, item)) { | |
n++ | |
if (n > 3) { | |
break | |
} | |
} | |
} | |
if (willLive(n)) { | |
newCells.push(neighbor) | |
} | |
} | |
} | |
return newCells | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment