-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolver.ts
74 lines (63 loc) · 1.87 KB
/
solver.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { PuzzleSolver } from "../types/puzzle-solver.ts";
type CubeGame = {
id: number;
sets: CubeSet[];
};
type CubeSet = {
red: number;
green: number;
blue: number;
};
export default class Solver23D2 implements PuzzleSolver {
private games: CubeGame[] = [];
parseInput(input: string[]) {
this.games = input.filter((line) => !!line).map(parseGame);
}
solvePart1() {
const sum = this.games.reduce((acc, game) => {
if (isGamePossible(game)) {
return acc + game.id;
}
return acc;
}, 0);
return sum;
}
solvePart2() {
const sum = this.games.reduce(
(acc, game) => acc + calculatePower(game),
0
);
return sum;
}
}
function parseGame(line: string): CubeGame {
const [game, rawSets] = line.split(": ");
const id = parseInt(game.split(" ")[1], 10);
const sets = rawSets.split("; ").map((rawSet) => {
const set = rawSet.split(", ").reduce(
(acc, curr) => {
const [count, color] = curr.split(" ");
acc[color as keyof CubeSet] = parseInt(count, 10);
return acc;
},
{ red: 0, green: 0, blue: 0 } as CubeSet
);
return set;
});
return { id, sets };
}
function isGamePossible(game: CubeGame) {
const RED_LIMIT = 12;
const GREEN_LIMIT = 13;
const BLUE_LIMIT = 14;
return game.sets.every(
({ red, green, blue }) =>
red <= RED_LIMIT && green <= GREEN_LIMIT && blue <= BLUE_LIMIT
);
}
function calculatePower({ sets }: CubeGame): number {
const maxRed = Math.max(...sets.map(({ red }) => red));
const maxGreen = Math.max(...sets.map(({ green }) => green));
const maxBlue = Math.max(...sets.map(({ blue }) => blue));
return maxRed * maxGreen * maxBlue;
}