Skip to content

Instantly share code, notes, and snippets.

@ripesunflower
Last active January 4, 2016 01:26
Show Gist options
  • Save ripesunflower/c321af31e1241f6934e3 to your computer and use it in GitHub Desktop.
Save ripesunflower/c321af31e1241f6934e3 to your computer and use it in GitHub Desktop.
Unlimited Conway's Life | Codewars
let ArrayUtils = {}
ArrayUtils.getSquare = function(x, y) {
return Array.apply(null, Array(y)).map( () => Array.apply(null,
Array(x)).map(() => 0) );
};
ArrayUtils.crop = function(array) {
let top, bottom, left, right;
top = 0;
while (array[top] && array[top].every((e) => e === 0)) top += 1;
bottom = array.length - 1;
while (array[bottom] && array[bottom].every((e) => e === 0)) bottom -= 1;
left = 0;
while (array.every((e) => e[left] === 0)) left += 1;
right = array[0].length - 1;
while (array.every((e) => e[right] === 0)) right -= 1;
let result;
if (bottom < 0 || right < 0 ||
top >= array.length || left >= array.length)
result = [[]];
else
result = array.slice(top, bottom + 1)
.map((line) => line.slice(left, right + 1));
return result;
};
let Life = function(current = [[]]) {
this.current = current;
this.neighbourhood = [
[-1, -1], [0, -1], [1, -1],
[-1, 0], [1, 0],
[-1, 1], [0, 1], [1, 1]
];
// (-1) : Death; (0) : Same; (1) : Alive
// 0, 1, 2, 3, 4, 5, 6, 7, 8
this.rules = [-1, -1, 0, 1, -1, -1, -1, -1, -1];
}
Life.prototype.next = function(generations = 1) {
let count = 0;
while (count !== generations) {
let [width, height] = [this.current[0].length, this.current.length];
let next = ArrayUtils.getSquare(width + 2, height + 2);
for (let row = 0; row < next.length; row++)
for (let column = 0; column < next[0].length; column++) {
let neighbours = this.neighbourhood.reduce((sum, [x, y]) => {
let result = (this.current[row + y - 1]) ?
this.current[row + y - 1][column + x - 1] : undefined;
return (result) ? sum + result : sum;
}, 0);
let rule = this.rules[neighbours];
next[row][column] = (rule === -1) ? 0
: ((rule === 1) ? 1
: ((this.current[row - 1])
? ((this.current[row - 1][column - 1])
? this.current[row - 1][column - 1] : 0 )
: 0));
}
this.current = ArrayUtils.crop(next);
count += 1;
}
return this.current;
}
let getGeneration = (cells, generations) => (new Life(cells)).next(generations);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment