Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for [old] Life Counter by Sim0000
"use strict"
function lifeCounter(data, tick_n) {
const pos = (x,y) => x + "," + y
const offset = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]
live = []
for(y in data){
for(x in data[0]){
if(data[y][x]) live.push(pos(x, y))
}
}
for(tick = 0; tick < tick_n; tick++){
next_live = []
born_candidate = []
// Any live cell with two or three live neighbours lives on to the next generation.
for(xy of live){
p = xy.split(",")
count = 0
for(d of offset){
neighbor = pos(p[0] - d[0], p[1] - d[1])
if(live.indexOf(neighbor) >= 0){
count++
} else if(born_candidate.indexOf(neighbor) == -1){
born_candidate.push(neighbor)
}
}
if((count == 2 || count == 3) && next_live.indexOf(xy) == -1){
next_live.push(xy)
}
}
// Any dead cell with exactly three live neighbours becomes a live cell.
for(xy of born_candidate){
p = xy.split(",")
count = 0
for(d of offset){
neighbhor = pos(p[0] - d[0], p[1] - d[1])
if(live.indexOf(neighbhor) >= 0){
count++
}
}
if(count == 3 && next_live.indexOf(xy) == -1){
next_live.push(xy)
}
}
live = next_live.slice(0)
}
return live.length
}
var assert = require('assert');
if (!global.is_checking) {
assert.equal(lifeCounter([[0, 1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0]], 4), 15, "Example");
assert.equal(lifeCounter([[0, 1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0]], 15), 14, "Little later");
assert.equal(lifeCounter([[0, 1, 0],
[0, 0, 1],
[1, 1, 1]], 50), 5, "Glider");
assert.equal(lifeCounter([[1, 1, 0, 1, 1],
[1, 1, 0, 1, 1],
[0, 0, 0, 0, 0],
[1, 1, 0, 1, 1],
[1, 1, 0, 1, 1]], 100), 16, "Stones");
console.log("Coding complete? Click 'Check' to review your tests and earn cool rewards!");
}
July 11, 2016
Comments: