You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
1.9 KiB
JavaScript

4 years ago
const fs = require("fs");
const input = fs.readFileSync("input", "utf-8").trim();
const startPlane = input.split("\n").map((line) => line.split(""));
let pocket = [[startPlane]];
function main() {
for (let step = 1; step <= 6; step++) {
const countActive = cycle();
console.log(`After ${step} steps: ${countActive}`);
}
}
function cycle() {
let squareLength = pocket[0][0].length;
let countActive = 0;
const nextPocket = [];
for (let w = -1; w < pocket.length + 1; w++) {
const space = [];
for (let z = -1; z < pocket.length + 1; z++) {
const plane = [];
for (let x = -1; x < squareLength + 1; x++) {
const line = [];
for (let y = -1; y < squareLength + 1; y++) {
const nextState = getState(w, z, x, y);
if (nextState === "#") countActive++;
line.push(nextState);
}
plane.push(line);
}
space.push(plane);
}
nextPocket.push(space);
}
pocket = nextPocket;
return countActive;
}
function getState(pw, pz, px, py) {
let activeNeighbors = 0;
for (const w of range(pw - 1, pw + 2)) {
for (const z of range(pz - 1, pz + 2)) {
for (const x of range(px - 1, px + 2)) {
for (const y of range(py - 1, py + 2)) {
if (pw === w && pz === z && px === x && py === y) continue;
if (isActive(w, z, x, y)) activeNeighbors++;
}
}
}
}
// console.log(`${py},${px},${py}: ${activeNeighbors}`);
if (isActive(pw, pz, px, py)) {
return activeNeighbors === 2 || activeNeighbors === 3 ? "#" : ".";
} else {
return activeNeighbors === 3 ? "#" : ".";
}
}
function isActive(w, z, x, y) {
return pocket[w]?.[z]?.[x]?.[y] === "#";
}
function range(start, stop, increment = 1) {
if (typeof stop === "undefined") {
stop = start;
start = 0;
}
const r = [];
for (let i = start; i < stop; i += increment) {
r.push(i);
}
return r;
}
main();