Skip to content

Instantly share code, notes, and snippets.

@seriousManual
Created November 17, 2018 14:52
Show Gist options
  • Save seriousManual/c7668272aa19b4e3a8fae199e51e48e8 to your computer and use it in GitHub Desktop.
Save seriousManual/c7668272aa19b4e3a8fae199e51e48e8 to your computer and use it in GitHub Desktop.
function getGOL(size) {
return function(matrix) {
const result = [];
for (let x = 0; x < matrix.length; x++) {
result[x] = [];
for (let y = 0; y < matrix.length; y++) {
const count = countNeighbours(matrix, x, y);
const alive = matrix[x][y];
if (!alive) {
if (count === 3) result[x][y] = true;
} else {
if (count === 1 || count === 0) result[x][y] = false;
if (count === 2 || count === 3) result[x][y] = true;
if (count > 3) result[x][y] = false;
}
}
}
return result;
}
}
function countNeighbours(matrix, x, y) {
let count = 0;
let size = matrix.length;
let left = (x == 0) ? size-1 : x - 1;
let right = (x == size-1) ? 0 : x + 1;
let top = (y == size-1) ? 0 : y + 1;
let bottom = (y == 0) ? size-1 : y - 1;
console.log(x, y)
console.log(left, right, top, bottom);
if (matrix[left][y]) count++;
if (matrix[left][top]) count++;
if (matrix[x][top]) count++;
if (matrix[right][top]) count++;
if (matrix[right][y]) count++;
if (matrix[right][bottom]) count++;
if (matrix[x][bottom]) count++;
if (matrix[left][bottom]) count++;
return count;
}
module.exports = getGOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment