-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday03.ts
47 lines (42 loc) · 1.17 KB
/
day03.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
import type { Day } from './Day.ts';
export class DayImpl implements Day {
private readonly input: string;
constructor(input: string) {
this.input = this.parseInput(input);
}
parseInput(input: string) {
return input
.trim();
}
partOne() {
const regex = /mul\((?<left>\d+),(?<right>\d+)\)/g;
const matches = [...this.input.matchAll(regex)];
return matches
.map(({ groups }) => {
if (groups?.left && groups?.right) {
return Number(groups.left) * Number(groups.right);
}
return 0;
})
.reduce((acc, val) => acc + val, 0);
}
partTwo() {
const regex = /(?<mul>mul\((?<left>\d+),(?<right>\d+)\))|(?<do>do\(\))|(?<dont>don't\(\))/g;
const matches = [...this.input.matchAll(regex)];
let deactivate = false;
return matches
.map(({ groups }) => {
if (groups?.dont) {
deactivate = true;
}
if (groups?.do) {
deactivate = false;
}
if (!deactivate && groups?.left && groups?.right) {
return Number(groups.left) * Number(groups.right);
}
return 0;
})
.reduce((acc, val) => acc + val, 0);
}
}