Public
Edited
Sep 17, 2023
1 star
Insert cell
Insert cell
Insert cell
function wires(input) {
return input.map((w) => w.map((instr) => [instr[0], Number(instr.slice(1))]));
}
Insert cell
Insert cell
Insert cell
function addSegment([[x, y, d], p], [dir, len]) {
let location;
for (let i = d + 1; i <= d + len; i++) {
p.push(
dir === "R"
? [++x, y, i]
: dir === "L"
? [--x, y, i]
: dir === "U"
? [x, --y, i]
: dir === "D"
? [x, ++y, i]
: []
);
}
return [[x, y, d + len], p];
}
Insert cell
Insert cell
function path(wire) {
return wire.reduce(addSegment, [[0, 0, 0], []])[1];
}
Insert cell
Insert cell
function toStr([x, y, d]) {
return x + "," + y;
}
Insert cell
function fromStr(str) {
return str.split(",").map(Number);
}
Insert cell
function intersectingWires([path1, path2]) {
return AOC.intersection(new Set(path1.map(toStr)), new Set(path2.map(toStr)));
}
Insert cell
Insert cell
function manhattan([x, y]) {
return Math.abs(x) + Math.abs(y);
}
Insert cell
function part1(input) {
const cDists = [...intersectingWires(wires(input).map(path))].map((s) =>
manhattan(fromStr(s))
);
return Math.min(...cDists);
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function part2(input) {
const [p1, p2] = wires(input).map(path);
const crossings = intersectingWires([p1, p2]);
const distances = (p) =>
p
.filter(([x, y, d]) => crossings.has(toStr([x, y])))
.sort((a, b) => manhattan(a) - manhattan(b))
.map(([x, y, d]) => d);

return Math.min(
...AOC.zipWith((a, b) => a + b, distances(p1), distances(p2))
);
}
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