Public
Edited
Dec 1, 2023
Insert cell
Insert cell
Insert cell
dVectors = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0]
]
Insert cell
Insert cell
function distFromOrigin(instructions) {
let [dir, pos] = [0, [0, 0]];
for (const instr of instructions) {
const blocks = Number(instr.slice(1));
dir = instr[0] === "R" ? (dir + 1) % 4 : (dir + 3) % 4;
pos[0] += blocks * dVectors[dir][0];
pos[1] += blocks * dVectors[dir][1];
}
return manhattan(pos);
}
Insert cell
Insert cell
function manhattan(pos) {
return Math.abs(pos[0]) + Math.abs(pos[1]);
}
Insert cell
function part1(input) {
return distFromOrigin(puzzleInput.split(", "));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function distFromFirstRevisit(instructions) {
let [dir, pos] = [0, [0, 0]];
const visited = new Set(["0,0"]);

for (const instr of instructions) {
const blocks = Number(instr.slice(1));
dir = instr[0] === "R" ? (dir + 1) % 4 : (dir + 3) % 4;
for (let i = 0; i < blocks; i++) {
pos[0] += dVectors[dir][0];
pos[1] += dVectors[dir][1];
const posTxt = pos[0] + "," + pos[1];
if (visited.has(posTxt)) {
return manhattan(pos);
}
visited.add(posTxt);
}
}
}
Insert cell
function part2(input) {
return distFromFirstRevisit(puzzleInput.split(", "));
}
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