Public
Edited
Dec 5, 2023
Insert cell
Insert cell
Insert cell
function parse(input) {
return input.split("\n").map((line) => {
const matches = line.match(/Card\s+(\d+):\s+([\d\s]+)\|\s+([\d\s]+)/);
return {
id: Number(matches[1]),
win: new Set(matches[2].split(/\s+/).map(Number)),
nums: new Set(matches[3].split(/\s+/).map(Number))
};
});
}
Insert cell
Insert cell
function scoreCards(cards) {
return cards.reduce((total, card) => {
const matches = AOC.intersection(card.win, card.nums).size;
return total + (matches ? 2 ** (matches - 1) : 0);
}, 0);
}
Insert cell
function part1(input) {
return scoreCards(parse(input));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function newIds(card, maxId) {
return d3.range(
card.id + 1,
Math.min(
card.id + 1 + AOC.intersection(card.win, card.nums).size,
maxId + 1
)
);
}
Insert cell
Insert cell
function countCards(input) {
const [fTable, maxId] = [new Map(), input.length];
for (const card of parse(input)) {
AOC.addToFreqTable(fTable, card.id);
for (const id of newIds(card, maxId)) {
AOC.addToFreqTable(fTable, id, fTable.get(card.id));
}
}
return AOC.sum([...fTable.values()]);
}
Insert cell
function part2(input) {
return countCards(input);
}
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