-
Notifications
You must be signed in to change notification settings - Fork 0
/
day_2.js
73 lines (65 loc) · 1.44 KB
/
day_2.js
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
const fs = require("node:fs");
fs.readFile("./day_2.txt", "utf8", (err, data) => {
if (err) {
console.error(err);
return;
}
lines = data.split("\n");
games = createGames(lines);
console.log(part2(games));
});
function part1(games) {
result = 0;
for (const game of games) {
if (isGameValid(game)) {
result += game.id;
}
}
return result;
}
function part2(games) {
power = 0;
for (const game of games) {
power +=
getPower(game.set, "red") *
getPower(game.set, "green") *
getPower(game.set, "blue");
}
return power;
}
function getPower(draws, color) {
const values = draws.map((draw) =>
draw[color] == undefined ? 0 : draw[color]
);
return Math.max(...values);
}
function isGameValid(game) {
for (const draw of game.set) {
if (draw.red > 12 || draw.green > 13 || draw.blue > 14) {
return false;
}
}
return true;
}
function createGames(lines) {
let result = [];
for (const line of lines) {
const [game, draws] = line.split(": ");
const gameId = parseInt(game.split(" ")[1]);
const gameSet = draws
.split("; ")
.map((draw) => draw.split(", ").map((cube) => cube.split(" ")))
.map((draw) =>
draw.reduce((acc, cur) => {
const [count, color] = cur;
acc[color] = parseInt(count);
return acc;
}, {})
);
result.push({
id: gameId,
set: gameSet,
});
}
return result;
}