Published unlisted
Edited
Dec 3, 2019
1 star
Insert cell
Insert cell
txt = (await (await fetch(
'https://gist.githubusercontent.com/bryangingechen/e666d26ed3842b459184441cc99dfcab/raw/b1459963add82b5099d48dc41b3b3764ed201c1a/2019%2520day%252003'
)).text()).slice(0, -1)
Insert cell
function wire(s) {
let pos = [[0, 0]];
for (const w of s.split(',')) {
const [lastx, lasty] = pos[pos.length - 1];
pos = pos.concat(
Array.from({ length: parseInt(w.slice(1)) }, (_, i) => [
lastx + (i + 1) * (w[0] === 'R' ? 1 : w[0] === 'L' ? -1 : 0),
lasty + (i + 1) * (w[0] === 'U' ? 1 : w[0] === 'D' ? -1 : 0)
])
);
}
return pos;
}
Insert cell
wires = txt.split('\n').map(wire)
Insert cell
function closestIntersection(wire1, wire2) {
const visited = new Set(wire1.map(a => JSON.stringify(a)));
const intersections = new Map();
let dist = Infinity;
let closest;
for (const p of wire2) {
const key = JSON.stringify(p);
if (visited.has(key)) {
const n = Math.abs(p[0]) + Math.abs(p[1]);
intersections.set(key, n);
if (n < dist && n > 0) {
dist = n;
closest = p.slice();
}
}
}
return { dist, closest, intersections };
}
Insert cell
part1 = closestIntersection(wires[0], wires[1])
Insert cell
function lowestIntersection(wire1, wire2) {
const visited = new Map();
const intersections = new Map();
let delay = Infinity;
let closest;
for (let i = 0; i < wire1.length; i++) {
const key = JSON.stringify(wire1[i]);
if (!visited.has(key)) {
visited.set(key, i);
}
}
for (let j = 0; j < wire2.length; j++) {
const key = JSON.stringify(wire2[j]);
if (visited.has(key)) {
const curr = j + visited.get(key);
intersections.set(key, curr);
if (curr < delay && curr > 0) {
closest = wire2[j].slice();
delay = curr;
}
}
}
return { delay, closest, intersections };
}
Insert cell
part2 = lowestIntersection(wires[0], wires[1])
Insert cell
function drawWire(ctx, p, h, scale, style) {
ctx.beginPath();
ctx.moveTo(h / 2, h / 2);
ctx.strokeStyle = style;
for (let i = 0; i < p.length; i++) {
ctx.lineTo(scale * p[i][0] + h / 2, scale * p[i][1] + h / 2);
}
ctx.stroke();
}
Insert cell
function draw(wire1, wire2, ints, h, scale) {
const ctx = DOM.context2d(h, h);
ctx.lineWidth = 1;
ctx.fillStyle = 'black';
drawWire(ctx, wire1, h, scale, 'red');
drawWire(ctx, wire2, h, scale, 'blue');
ctx.beginPath();
ctx.arc(h / 2, h / 2, 2, 0, 2 * Math.PI);
ctx.fill();
ctx.fillStyle = 'green'; // TODO: color according to score?
for (const intMap of ints) {
for (const [key, val] of intMap) {
if (key === '[0,0]') continue;
const p = JSON.parse(key);
ctx.beginPath();
ctx.arc(p[0] * scale + h / 2, p[1] * scale + h / 2, 2, 0, 2 * Math.PI);
ctx.fill();
}
}
return ctx.canvas;
}
Insert cell
draw(wires[0], wires[1], [part1.intersections], 500, .021)
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