-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday07.ts
56 lines (47 loc) · 1.57 KB
/
day07.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 type { Day } from './Day.ts';
export class DayImpl implements Day {
private readonly input: Array<Array<number>>;
constructor(input: string) {
this.input = this.parseInput(input);
}
parseInput(input: string) {
return input
.trim()
.split('\n')
.map((line: string) => {
return line.match(/\d+/g)!
.map(Number);
});
}
partOne() {
return this.input.map(line => isValidLine(line, false)).reduce((acc, val) => acc + val, 0);
}
partTwo() {
return this.input.map(line => isValidLine(line, true)).reduce((acc, val) => acc + val, 0);
}
}
function isValidLine(line: number[], withConcat: boolean) {
const [total, ...numbers] = line;
const first = numbers.shift()!;
const queue: { result: number; numbers: number[] }[] = [{ result: first, numbers }];
while (queue.length > 0) {
const curr = queue.shift()!;
const currNumber = curr.numbers.shift()!;
const totalAdd = curr.result + currNumber;
const totalMultiply = curr.result * currNumber;
const totalConcat = Number(`${curr.result}${currNumber}`);
if (curr.numbers.length === 0 && (totalAdd === total || totalMultiply === total || totalConcat === total)) {
return total;
}
if (totalAdd <= total) {
queue.push({ result: totalAdd, numbers: [...curr.numbers] });
}
if (totalMultiply <= total) {
queue.push({ result: totalMultiply, numbers: [...curr.numbers] });
}
if (withConcat && totalConcat <= total) {
queue.push({ result: totalConcat, numbers: [...curr.numbers] });
}
}
return 0;
}