Public
Edited
Dec 14, 2023
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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more