Public
Edited
Dec 2, 2023
1 star
Insert cell
Insert cell
Insert cell
function parse(input) {
const games = {};
for (const game of input.split("\n")) {
const [gameTxt, cubeTxt] = game.split(": ");
const id = gameTxt.split(" ")[1];
games[id] = cubeTxt.split("; ").map((round) =>
round.split(", ").reduce((acc, cube) => {
const [n, clr] = cube.split(" ");
acc[clr] = (acc[clr] || 0) + Number(n);
return acc;
}, {})
);
}
return games;
}
Insert cell
Insert cell
function possibleGames(games) {
const [minR, minG, minB] = [12, 13, 14];
const notAbove = (x, cap) => x === undefined || x <= cap;

return Object.entries(games).reduce((total, [id, game]) => {
const possible = game.every(
(round) =>
notAbove(round.red, minR) &&
notAbove(round.green, minG) &&
notAbove(round.blue, minB)
);
return total + (possible ? +id : 0);
}, 0);
}
Insert cell
function part1(input) {
return possibleGames(parse(input));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function minPower(games) {
let total = 0;
for (const [id, game] of Object.entries(games)) {
let [maxR, maxG, maxB] = [0, 0, 0];
for (const round of game) {
maxR = d3.max([round.red, maxR]);
maxG = d3.max([round.green, maxG]);
maxB = d3.max([round.blue, maxB]);
}
total += maxR * maxG * maxB;
}
return total;
}
Insert cell
function part2(input) {
return minPower(parse(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
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