-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsumValidMuls.ts
31 lines (26 loc) · 955 Bytes
/
sumValidMuls.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
const reInstruction = /^|do\(\)|don't\(\)|$/g;
const reInstructionDo = /^do\(\)/;
const reValidMuls = /mul\((\d{1,3}),(\d{1,3})\)/g;
export function getInstructionsDo(str: string): string[] {
return [...str.matchAll(reInstruction)]
.map((x) => x.index)
.map((e, i, a) => [e, a[i + 1]])
.map((x) => str.substring(x[0], x[1]))
.filter((e, i) => reInstructionDo.test(e) || i == 0);
}
export function getValidMuls(str: string): number[][] {
return [...str.matchAll(reValidMuls)]
.map((x) => [x[1], x[2]].map((y) => parseInt(y)));
}
export function sumMuls(array: number[][]): number {
return array.reduce((sum, current) => sum + (current[0] * current[1]), 0);
}
export function sumValidMuls(str: string): number {
return sumMuls(getValidMuls(str));
}
export function sumValidMulsDo(str: string): number {
return getInstructionsDo(str)
.map(getValidMuls)
.map(sumMuls)
.reduce((sum, current) => sum + current);
}