Public
Edited
Dec 5, 2021
1 star
Insert cell
Insert cell
Insert cell
function parse(input) {
return input.map((s) =>
s
.match(/(\d+),(\d+) -> (\d+),(\d+)/)
.slice(1, 5)
.map(Number)
);
}
Insert cell
Insert cell
Insert cell
function orthogonal(endpoints) {
return endpoints.filter(([x1, y1, x2, y2]) => x1 == x2 || y1 == y2);
}
Insert cell
Insert cell
function lineCoords([x1, y1, x2, y2]) {
const xInc = Math.sign(x2 - x1);
const yInc = Math.sign(y2 - y1);
const numSteps = Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)) + 1;
const coords = [];

for (let i = 0; i < numSteps; i++) {
coords.push([x1 + i * xInc, y1 + i * yInc]);
}
return coords;
}
Insert cell
Insert cell
function intersections(lines) {
const toStr = ([x, y]) => x + "," + y;
const coords = lines.map(lineCoords).flat().map(toStr);
const ft = new Map();
coords.forEach((c) => AOC.addToFreqTable(ft, c));
return [...ft].filter(([_, freq]) => freq > 1).length;
}
Insert cell
function part1(input) {
return intersections(orthogonal(parse(input)));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function part2(input) {
return intersections(parse(input));
}
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