Skip to content

Instantly share code, notes, and snippets.

@PetrSnobelt
Created November 13, 2015 15:11
Show Gist options
  • Save PetrSnobelt/56646424317c2db6c209 to your computer and use it in GitHub Desktop.
Save PetrSnobelt/56646424317c2db6c209 to your computer and use it in GitHub Desktop.
Javascript ES5 GOL
function flat(arr){
return [].concat.apply([], arr);
}
//can be created by simple array
function nearNeighbours() {
var all = [-1, 0, 1].map(function (y) {
return [-1, 0, 1].map(function (x) {
return [(x), (y)];
});
});
return flat(all).filter(function (i) {
return i[0] !== 0 || i[1] !== 0;
});
}
function neighbours (x, y) {
return nearNeighbours().map(function (i) {
return [(x + i[0]), (y + i[1])];
});
}
function contain(c, gen) {
return gen.some(function(f){
return (f[0] === c[0] && f[1] === c[1])
});
}
function liveNeighbours(pos, gen) {
return neighbours(pos[0], pos[1]).reduce(function(p, c){
var found = contain(c, gen);
p = p + (found ? 1 : 0);
return p;
},0);
}
function rule(liveNeighbours, isAlive) {
return liveNeighbours == 3 || (liveNeighbours == 2 && isAlive);
}
function expand(gen){
return gen.reduce(function(p, c) {
neighbours(c[0],c[1]).map(function(i){
if (!contain(i, p)) p.push(i);
});
return p;
},[]);
}
function gol(gen){
var all = expand(gen);
return all.reduce(function(p, c) {
var n = liveNeighbours(c, gen);
var found = contain(c, gen);
if (rule(n, found)) p.push(c);
return p;
},[]);
}
var blinker = [[0,0], [0,1], [0,2]];
gol(gol(blinker));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment