-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday2.ts
92 lines (80 loc) · 2.8 KB
/
day2.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { assertEquals } from "https://deno.land/std@0.208.0/assert/mod.ts";
import { loadTestData, loadData } from "./utils.ts";
const part1test = 8;
const part2test = 2286;
const part1 = (data: string) => {
const lines = data.split("\n");
const maxRed = 12;
const maxGreen = 13;
const maxBlue = 14;
let sum = 0;
for (const line of lines) {
const parts = line.split(": ");
const id = parseInt(parts[0].substring(5));
const rounds = parts[1].split("; ").map(round => round.split(", ").map(item => item.split(" ")));
let impossible = false;
for (const round of rounds) {
for (const item of round) {
switch (item[1]) {
case "red":
if (parseInt(item[0]) > maxRed) {
impossible = true;
}
break;
case "blue":
if (parseInt(item[0]) > maxBlue) {
impossible = true;
}
break;
case "green":
if (parseInt(item[0]) > maxGreen) {
impossible = true;
}
break;
}
}
}
if (!impossible) {
sum += id;
}
}
return sum;
};
const part2 = (data: string) => {
const lines = data.split("\n");
let sum = 0;
for (const line of lines) {
const parts = line.split(": ");
const id = parseInt(parts[0].substring(5));
const rounds = parts[1].split("; ").map(round => round.split(", ").map(item => item.split(" ")));
let largestRed = 0;
let largestGreen = 0;
let largestBlue = 0;
for (const round of rounds) {
for (const item of round) {
switch (item[1]) {
case "red":
if (parseInt(item[0]) > largestRed) {
largestRed = parseInt(item[0]);
}
break;
case "blue":
if (parseInt(item[0]) > largestBlue) {
largestBlue = parseInt(item[0]);
}
break;
case "green":
if (parseInt(item[0]) > largestGreen) {
largestGreen = parseInt(item[0]);
}
}
}
}
sum += largestRed * largestGreen * largestBlue;
}
return sum;
};
assertEquals(part1(await loadTestData(2)), part1test)
console.log(part1(await loadData(2)))
assertEquals(part2(await loadTestData(2)), part2test)
console.log(part2(await loadData(2)))