aoc-2023/day_2/solve_2.ts

59 lines
1.8 KiB
TypeScript
Raw Permalink Normal View History

2024-12-09 22:41:02 +09:00
const input = await Deno.readTextFile("input.txt");
// const input = `Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
// Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
// Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
// Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
// Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green`;
const lines = input.split("\n");
type ColorBox = {
green: number;
red: number;
blue: number;
}
function parseInput(line: string){
const m = /Game (\d+):/.exec(line);
if (!m) {
throw new Error("Invalid line: " + line)
}
const id = parseInt(m[1]);
const rest = line.slice(m[0].length);
const obj = rest.split(";").map(colorStr => {
const obj: ColorBox = {
red: 0,
green: 0,
blue: 0
};
const colors = colorStr.split(",");
colors.forEach(x=> {
const [number, color] = x.trim().split(" ");
if (["blue", "green", "red"].indexOf(color) === -1) {
throw new Error("Invalid color: " + color);
}
obj[color as keyof ColorBox] = parseInt(number);
});
return obj;
});
return {
id,
colorSets: obj
}
}
const games = lines.map(parseInput);
const availGames = games.map(game=> game.colorSets.reduce((a, b) =>{
return {
red: Math.max(a.red , b.red),
green: Math.max(a.green , b.green),
blue: Math.max(a.blue , b.blue)
}
}, {
red: 0,
green: 0,
blue: 0
}));
const powersOfGames = availGames.map(x=> x.red * x.green * x.blue);
const sum = powersOfGames.reduce((a, b) => a + b, 0);
console.log(availGames, sum)