Public
Edited
Dec 13, 2023
1 fork
1 star
Insert cell
Insert cell
Insert cell
lines = input
.split("\n")
.map((line) =>
(([line, groups]) => ({ line, groups: groups.split(",").map(Number) }))(
line.split(" ")
)
)
Insert cell
function enumerate({ line, groups, size = 0, memo = new Map() }) {
const key = `${line.length} ${groups.length} ${size}`;
if (!memo.has(key)) {
const u = line[0];
line = line.slice(1);
memo.set(
key,
u
? (u === "#" // not a •, exit
? null
: size === 0 // not in a group, advance
? enumerate({ line, groups, size: 0, memo })
: size === groups[0] // in a finished group, close it
? enumerate({ line, groups: groups.slice(1), size: 0, memo })
: null) +
(u === "." // not a #, exit
? null
: size === 0 // enter a new group
? enumerate({ line, groups, size: 1, memo })
: size === groups[0] // current group was already at size, it's invalid to add a #
? null
: enumerate({ line, groups, size: size + 1, memo })) // advance in that group
: // end of line?
(size === 0 && groups.length === 0) || // not in group
(groups.length === 1 && size === groups[0]) // closing the last group
);
}
return memo.get(key);
}
Insert cell
d3.sum(lines, enumerate) // 7792
Insert cell
Insert cell
fold = n => ({ line, groups }) => ({
line: Array(n).fill(line).join("?"),
groups: Array(n).fill(groups).flat()
})
Insert cell
d3.sum(lines.map(fold(5)), enumerate) // 13012052341533
Insert cell
Insert cell
Plot.lineY(d3.range(1, 6), {
x: Plot.identity,
y: (i) => d3.sum(lines.map(fold(i)), enumerate),
marker: true
}).plot({ y: { type: "log", grid: true } })
Insert cell
Plot.lineY(d3.cross(d3.range(1, 6), lines), {
x: ([i]) => i,
y: ([i, line]) => enumerate(fold(i)(line)),
stroke: ([, { line, groups }], j) => j % lines.length, //line + groups,
strokeWidth: 0.2,
tip: true
}).plot({ y: { type: "log", grid: true } })
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