Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
"Life Counter" with small optimization solution in Clear category for [old] Life Counter by capback250
"use strict";
const SIDES = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];
/**
* used while for optimization
* @param who
* @param where
* @returns {boolean}
*/
const checkIn = (who, where) => {
let i = where.length;
while (i--) {
if (where[i][0] === who[0] && where[i][1] === who[1]) return true
}
return false;
};
const init = marbles => {
let alive = [];
for (let i = 0; i < marbles.length; i++) {
for (let j = 0; j < marbles[0].length; j++) {
if (marbles[i][j] === 1) alive.push([i, j])
}
}
return alive;
};
const neibors = point => {
let [x, y] = point;
return SIDES.map(side => {
let [dx, dy] = side;
return [x + dx, y + dy]
})
};
const aliveAtround = (point, state) => neibors(point)
.map(neibor => checkIn(neibor, state) ? 1 : 0)
.reduce((a, b) => a + b, 0);
function lifeCounter(marbles, step) {
let lifeTracker = {0: init(marbles)};
for (let i = 1; i <= step; i++) {
let currentLive = lifeTracker[i - 1];
let willLive = [];
currentLive.map(point => {
neibors(point).map(p => {
if (!checkIn(p, willLive) && !checkIn(p, currentLive) && aliveAtround(p, currentLive) === 3) willLive.push(p)
});
if (!checkIn(point, willLive) && [2, 3].includes(aliveAtround(point, currentLive))) willLive.push(point);
});
lifeTracker[i] = willLive;
}
return lifeTracker[step].length
}
May 17, 2017