Public
Edited
Dec 3, 2023
Insert cell
Insert cell
Insert cell
map = {
const map = new d3.InternMap([], String);
let n = {};
for (const [y, line] of input.trim().split("\n").entries())
for (const [x, c] of [...line].entries())
if (c === ".") {
n = {};
} else if (isNaN(Number(c))) {
n = {};
map.set([x, y], c);
} else {
n.s = (n.s ?? "") + c;
map.set([x, y], { n, digit: c });
}
return map;
}
Insert cell
symbols = d3.filter(map.entries(), ([p, c]) => typeof c === "string")
Insert cell
function* neighbors([x, y]) {
for (const dx of [-1, 0, 1])
for (const dy of [-1, 0, 1])
if (dx !== 0 || dy !== 0) yield [x + dx, y + dy];
}
Insert cell
partNumbers = {
const numbers = new Set();
for (const [p] of symbols) {
for (const n of neighbors(p)) {
const v = map.get(n);
if (v && v.n) numbers.add(v.n);
}
}
return numbers;
}
Insert cell
part1 = d3.sum(partNumbers, d => +d.s)
Insert cell
gears = {
const gears = [];
for (const [p, c] of symbols) {
if (c !== "*") continue;
const numbers = new Set(
d3.map(neighbors(p), (n) => map.get(n)?.n).filter((d) => d)
);
if (numbers.size === 2) gears.push([...numbers]);
}
return gears;
}
Insert cell
part2 = d3.sum(gears.map(([a, b]) => +a.s * +b.s))
Insert cell
sample = `
467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598..
`
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