-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.mjs
68 lines (57 loc) · 1.47 KB
/
2.mjs
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
import { readInput } from "./utils.mjs";
const input = readInput(import.meta);
const goal = {
red: 12,
green: 13,
blue: 14,
};
const colors = ["red", "green", "blue"];
const isValidSubset = (subset) =>
colors.every((color) => goal[color] >= (subset[color] || 0));
const isValidGame = (game) => game.every(isValidSubset);
const parseInput = (input) =>
input
.split("\n")
.map((line) => line.split(": ")[1])
.map((line) =>
line.split("; ").map((subset) =>
[...subset.matchAll(/(\d+) (blue|red|green)/g)].reduce(
(subsetObj, [, numString, color]) => ({
...subsetObj,
[color]: +numString,
}),
{},
),
),
);
const solve1 = (input) => {
const games = parseInput(input);
return games.reduce(
(acc, game, i) => (isValidGame(game) ? acc + i + 1 : acc),
0,
);
};
const solve2 = (input) => {
const games = parseInput(input);
const maxesByGame = games.map((game) =>
game.reduce(
(maxesByColor, subset) => ({
red: Math.max(subset.red ?? 0, maxesByColor.red),
green: Math.max(subset.green ?? 0, maxesByColor.green),
blue: Math.max(subset.blue ?? 0, maxesByColor.blue),
}),
{
red: 0,
green: 0,
blue: 0,
},
),
);
return maxesByGame.reduce(
(result, game) =>
result + Object.values(game).reduce((acc, val) => acc * val, 1),
0,
);
};
console.log(solve1(input));
console.log(solve2(input));