Public
Edited
Oct 2, 2023
1 fork
1 star
Insert cell
Insert cell
Insert cell
function findPath(diagram) {
let [x, y, dx, dy] = [diagram[0].indexOf("|"), 0, 0, 1]; // Start on top row at first vertical pipe facing down.
let letters = "";
let steps = 0;

while (true) {
// Move one step
x += dx;
y += dy;
steps++;
const cell = diagram[y][x];

if (cell === " ") {
return { letters, steps }; // We've come to end of pipe.
}

// Collect letter
if (cell.match(/[A-Z]/)) {
letters += cell;
}

// Change direction at corners.
if (cell === "+") {
[dy, dx] =
dy === 0
? [(dy = diagram[y + 1][x] === " " ? -1 : 1), 0]
: ([dy, dx] = [0, diagram[y][x + 1] === " " ? -1 : 1]);
}
}
}
Insert cell
function part1(input) {
return findPath(input.split("\n")).letters;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function part2(input) {
return findPath(input.split("\n")).steps;
}
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