Public
Edited
Dec 2
Paused
1 fork
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function parse(input) {
return input.split("\n").map((instr) => {
const [, dir, len] = instr.match(/([UDLR])\s+(\d+)/);
return { dir: dir, len: Number(len) };
});
}
Insert cell
Insert cell
function toPoly(instrs) {
const vertices = [[0, 0]];
let [x, y] = [0, 0];
instrs.forEach((v) => {
switch (v.dir) {
case "L":
x -= v.len;
break;
case "R":
x += v.len;
break;
case "U":
y -= v.len;
break;
case "D":
y += v.len;
break;
}
vertices.push([x, y]);
});
return vertices;
}
Insert cell
Insert cell
Insert cell
Insert cell
function polyData(instrs) {
const polygon = toPoly(instrs);
const area = Math.abs(d3.polygonArea(polygon)); // abs so we can ignore winding order.
const perimeter = AOC.sum(instrs.map((d) => d.len));
return {
polygon: polygon,
perimeter: perimeter,
area: area,
griddedArea: area + perimeter / 2 + 1
};
}
Insert cell
function part1(input) {
return polyData(parse(input)).griddedArea;
}
Insert cell
Insert cell
Insert cell
Insert cell
function parse2(input) {
const hexToInstr = (hex) => {
const len = parseInt(hex.slice(2, -2), 16);
let dir;
switch (hex.slice(-2, -1)) {
case "0":
dir = "R";
break;
case "1":
dir = "D";
break;
case "2":
dir = "L";
break;
case "3":
dir = "U";
break;
}
return { dir: dir, len: len };
};
return input.split("\n").map((line) => hexToInstr(line.split(/\s+/)[2]));
}
Insert cell
Insert cell
function part2(input) {
return polyData(parse2(input)).griddedArea;
}
Insert cell
Insert cell
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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