Created
December 5, 2018 18:34
-
-
Save evilj0e/2b4d3388772d8401f28f2d942769ff6c to your computer and use it in GitHub Desktop.
This file contains hidden or 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 currentField = ['0:1', '1:1', '2:1']; | |
function parseItem(item) { | |
return item.split(':').map(Number); // [ x, y ] | |
} | |
function countNeighbours(x, y) { | |
let sum = 0; | |
for(var t = -1; t <= 1; t++){ | |
for(var r = -1; r <= 1; r++){ | |
if (!t && !r) { | |
continue; | |
} | |
if (currentField.indexOf(`${x + t}:${y + r}`) !== -1) { | |
sum++; | |
} | |
} | |
} | |
return sum; | |
} | |
function cellIsAlive(count, state) { | |
if (count < 2 || count > 3) { | |
return false; | |
} | |
if (count === 2) { | |
return Boolean(state); | |
} | |
return true; | |
} | |
function step(array) { | |
const nextField = []; | |
const parsedArray = array.map(parseItem); | |
for(let i = -1; i <= 1; i++) { | |
for(let j = -1; j <= 1; j++) { | |
parsedArray.forEach(function(point) { // [x, y] | |
const nextX = point[0] + i; | |
const nextY = point[1] + j; | |
const isCurrentAlive = array.indexOf(`${nextX}:${nextY}`) !== -1; | |
if (cellIsAlive(countNeighbours(nextX, nextY), isCurrentAlive)) { | |
if (nextField.indexOf(`${nextX}:${nextY}`) === -1) { | |
nextField.push(`${nextX}:${nextY}`); | |
} | |
} | |
}) | |
} | |
} | |
return nextField; | |
} | |
console.log(step(currentField)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment