Day 2 solutions 😊😊😊

This commit is contained in:
Peter 2023-12-02 16:52:29 +08:00
parent 1080d8a2c5
commit 60cbaac7df
3 changed files with 86 additions and 0 deletions

41
day_2/parser.ts Normal file
View File

@ -0,0 +1,41 @@
export interface Turn {
red: number;
green: number;
blue: number;
}
export interface Game {
id: number;
turns: Turn[];
}
export const parse_file = (input: string) => {
return input.split("\n").map((line) => {
const game: Game = { id: -1, turns: [] };
const parts = line.replace(/^Game /, "").split(":");
game.id = parseInt(parts[0]);
const turns = parts[1].split(";");
turns.map((turn) => {
const turn_struct: Turn = { red: 0, green: 0, blue: 0 };
turn
.trim()
.split(",")
.forEach((part) => {
const value = parseInt(part.trim().split(" ")[0]);
switch (part.trim().split(" ")[1]) {
case "red":
turn_struct.red = value;
break;
case "green":
turn_struct.green = value;
break;
case "blue":
turn_struct.blue = value;
break;
}
});
game.turns.push(turn_struct);
});
return game;
});
};

23
day_2/part_1.ts Normal file
View File

@ -0,0 +1,23 @@
import * as fs from "fs";
import { Game, Turn, parse_file } from "./parser";
const MAX_CUBES: Turn = { red: 12, green: 13, blue: 14 };
const input = fs.readFileSync("input", "utf8");
const sum_possible_games = parse_file(input)
.map((game) =>
game.turns.reduce(
(valid, turn) =>
valid &&
turn.blue <= MAX_CUBES.blue &&
turn.red <= MAX_CUBES.red &&
turn.green <= MAX_CUBES.green,
true
)
? game.id
: 0
)
.reduce((sum, game_id) => sum + game_id, 0);
console.log(sum_possible_games);

22
day_2/part_2.ts Normal file
View File

@ -0,0 +1,22 @@
import * as fs from "fs";
import { Game, Turn, parse_file } from "./parser";
const input = fs.readFileSync("input", "utf8");
const total_power = parse_file(input)
.map((game) => {
const min_cubes = game.turns.reduce(
(min_cubes, turn) => {
return {
blue: Math.max(turn.blue, min_cubes.blue),
red: Math.max(turn.red, min_cubes.red),
green: Math.max(turn.green, min_cubes.green),
};
},
{ red: 0, blue: 0, green: 0 }
);
return min_cubes.blue * min_cubes.green * min_cubes.red;
})
.reduce((total_power, game_power) => total_power + game_power, 0);
console.log(total_power);