Public
Edited
Nov 19, 2022
1 star
Insert cell
Insert cell
Insert cell
Insert cell
function toVector(dir) {
switch (dir) {
case "e":
return [0, 1, 1];
case "se":
return [-1, 1, 0];
case "sw":
return [-1, 0, -1];
case "w":
return [0, -1, -1];
case "nw":
return [1, -1, 0];
case "ne":
return [1, 0, 1];
}
}
Insert cell
Insert cell
function parse(input) {
const re = /(n.)|(s.)|(w)|(e)/g;
return input.map((s) => s.match(re).map(toVector));
}
Insert cell
Insert cell
function move(vs) {
return vs.reduce(
([x, y, z], [dx, dy, dz]) => [x + dx, y + dy, z + dz],
[0, 0, 0]
);
}
Insert cell
Insert cell
function encode(arr) {
return JSON.stringify(arr);
}
Insert cell
function decode(str) {
return JSON.parse(str);
}
Insert cell
function countBlack(input) {
const fTable = new Map();
parse(input)
.map(move)
.forEach((pos) => AOC.addToFreqTable(fTable, encode(pos)));
return AOC.sum([...fTable.values()].filter((flips) => flips % 2 === 1));
}
Insert cell
function part1(input) {
return countBlack(puzzleInput);
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function neighbours(cell) {
const p = decode(cell);
return new Set(
["e", "se", "sw", "w", "nw", "ne"]
.map(toVector)
.map(([x, y, z]) => encode([p[0] + x, p[1] + y, p[2] + z]))
);
}
Insert cell
Insert cell
function rule(isAlive, n) {
return n === 2 || (isAlive && n === 1);
}
Insert cell
Insert cell
function live(cells, p) {
return rule(cells.has(p), AOC.intersection(neighbours(p), cells).size);
}
Insert cell
Insert cell
function generation(cells) {
let newCells = new Set();
[...cells].forEach((cell) => {
newCells = AOC.union(newCells, neighbours(cell));
return newCells.add(cell);
});
return new Set([...newCells].filter((p) => live(cells, p)));
}
Insert cell
Insert cell
function run(input) {
const fTable = new Map();
parse(input)
.map(move)
.forEach((pos) => AOC.addToFreqTable(fTable, encode(pos)));

// Initial cell configuration
let cells = new Set(
[...fTable.entries()]
.filter(([tile, flips]) => flips % 2 === 1)
.map(([pos, _]) => pos)
);

// Run the tile flipping 100 times
for (let i = 0; i < 100; i++) {
cells = generation(cells);
}
return cells.size;
}
Insert cell
function part2(input) {
// Process is quite slow (c.20 seconds) so returning correct value directly. Uncomment line below to run.
// return run(puzzleInput);
return 3519;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more