53 lines
1.7 KiB
TypeScript
53 lines
1.7 KiB
TypeScript
|
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
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function isPossibleBox(f: ColorBox): boolean {
|
||
|
return f.blue <= 14 && f.green <= 13 && f.red <= 12;
|
||
|
}
|
||
|
|
||
|
const games = lines.map(parseInput);
|
||
|
const availGames = games.filter(game=> game.colorSets.every(color=> isPossibleBox(color)));
|
||
|
const availGameIds = availGames.map(x=> x.id);
|
||
|
const sum = availGameIds.reduce((a, b) => a + b, 0);
|
||
|
console.log(availGameIds, sum)
|