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}`); if (step === 1 || step === 2) { printPocket(); } } } function cycle() { let squareLength = pocket[0].length; let countActive = 0; const nextPocket = []; 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(z, x, y); if (nextState === "#") countActive++; line.push(nextState); } plane.push(line); } nextPocket.push(plane); } pocket = nextPocket; return countActive; } function getState(pz, px, py) { let activeNeighbors = 0; 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 (pz === z && px === x && py === y) continue; if (isActive(z, x, y)) activeNeighbors++; } } } // console.log(`${py},${px},${py}: ${activeNeighbors}`); if (isActive(pz, px, py)) { return activeNeighbors === 2 || activeNeighbors === 3 ? "#" : "."; } else { return activeNeighbors === 3 ? "#" : "."; } } function isActive(z, x, y) { return pocket[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; } function printPocket() { for (const z in pocket) { const plane = pocket[z]; console.log(`z=${z}`); for (const line of plane) { console.log(line.join("")); } } } main();