Public
Edited
Dec 9, 2023
Insert cell
Insert cell
Insert cell
Insert cell
getDirections = (input) => input.split("\n\n")[0].split("")
Insert cell
getConnections= input=>input
.split("\n\n")[1]
.split("\n")
.reduce((con, line) => {
con[line.split(" = ")[0]] = {
L: line
.split(" = ")[1]
.replace(/[\(|\)]/g, "")
.split(", ")[0],
R: line
.split(" = ")[1]
.replace(/[\(|\)]/g, "")
.split(", ")[1]
};
return con;
}, {})
Insert cell
directions = getDirections(inputs)
Insert cell
connections = getConnections(inputs)
Insert cell
## Part 1
Insert cell
Insert cell
pathfinder = function* (directions, connections) {
let current = "AAA";
let steps = 0;
while (current != "ZZZ") {
for (let dir of directions) {
current = connections[current][dir];
steps++;
if (steps % 1000 == 0) {
yield steps;
}
}
}
yield steps;
}
Insert cell
result1 = pathfinder(directions, connections)
Insert cell
## Part 2
Insert cell
Insert cell
directions2= getDirections(inputs2)
Insert cell
connections2 = getConnections(inputs2)
Insert cell
ghostingCycles = function* (directions, connections) {
let currents = Object.keys(connections).filter(
(con) => con[con.length - 1] == "A"
);
let cycles = currents.map((c) => 0);
let steps = 0;
while (
cycles.filter((loop) => loop == 0).length > 0 &&
currents.filter((con) => con[con.length - 1] != "Z").length > 0
) {
for (let dir of directions) {
currents = currents.map((current, idx) => {
if (
steps % directions.length == 0 &&
current[current.length - 1] == "Z" &&
cycles[idx] == 0
) {
cycles[idx] = steps / directions.length;
}
return connections[current][dir];
});
steps++;
if (steps % 1000000 == 0) {
yield cycles;
}
}
}
yield cycles;
}
Insert cell
cycles = ghostingCycles(directions, connections)
Insert cell
result2 = cycles.reduce((prod, cycle) => prod * cycle, 1) * directions.length
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