Public
Edited
Dec 19
Paused
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function parse(input) {
const [towels, designs] = input.split("\n\n");
const tSet = new Set(towels.split(/,\s?/));
return [tSet, designs.split("\n"), d3.max(tSet, (d) => d.length)];
}
Insert cell
Insert cell
function isValid(tSet, design, mxLen) {
if (design.length === 0) {
return true;
}
for (let i = 1; i <= Math.min(design.length, mxLen); i++) {
if (tSet.has(design.slice(0, i)) && isValid(tSet, design.slice(i), mxLen)) {
return true;
}
}
return false;
}
Insert cell
Insert cell
function part1(input) {
const [tSet, designs, mxLen] = parse(puzzleInput);
return designs.filter((d) => isValid(tSet, d, mxLen)).length;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function arrangements(tSet, design, mxLen) {
const counts = Array(design.length + 1).fill(0);
counts[0] = 1; // Start with one way to construct an empty design

for (let j = 1; j <= design.length; j++) {
for (let i = Math.max(0, j - mxLen); i < j; i++) {
if (tSet.has(design.slice(i, j))) {
counts[j] += counts[i];
}
}
}
return counts.at(-1);
}
Insert cell
function part2(input) {
const [tSet, designs, mxLen] = parse(puzzleInput);
const validDesigns = designs.filter((d) => isValid(tSet, d, mxLen));
return AOC.sum(validDesigns.map((d) => arrangements(tSet, d, mxLen)));
}
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