-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathpart-two.ts
56 lines (47 loc) · 1.14 KB
/
part-two.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
import { input } from './input';
type DoCommand = {
index: number;
type: 'do';
};
type DontCommand = {
index: number;
type: 'dont';
};
type MulCommand = {
index: number;
type: 'mul';
product: number;
};
type Commands = DoCommand | DontCommand | MulCommand;
const commands: Array<Commands> = [];
let match: RegExpExecArray | null;
const doRegEx = /do\(\)/g;
while ((match = doRegEx.exec(input)) !== null) {
commands.push({ index: match.index, type: 'do' });
}
const dontRegEx = /don't\(\)/g;
while ((match = dontRegEx.exec(input)) !== null) {
commands.push({ index: match.index, type: 'dont' });
}
const mulRegExp = /mul\((\d{1,3}),(\d{1,3})\)/g;
while ((match = mulRegExp.exec(input)) !== null) {
const [, numA, numB] = match;
commands.push({
index: match.index,
type: 'mul',
product: parseInt(numA, 10) * parseInt(numB, 10),
});
}
commands.sort((a, b) => a.index - b.index);
let running = true;
let sum = 0;
for (let command of commands) {
if (command.type === 'do') {
running = true;
} else if (command.type === 'dont') {
running = false;
} else if (command.type === 'mul' && running) {
sum += command.product;
}
}
console.log(sum);