-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday7.ts
91 lines (79 loc) · 1.89 KB
/
day7.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
import { input } from './input';
const myInputs: Array<[number, number[]]> = input.split('\n').map((r) => {
const [answer, inputs] = r.split(':');
const parts = inputs
.split(' ')
.filter((i) => i.length > 0)
.map(Number);
return [Number(answer), parts];
});
type I = [number, number[]];
type operator = 'mult' | 'add' | 'concat';
function doWork(
cur: I,
operator: operator,
allowedOps: Array<operator>,
): boolean {
// console.log(cur);
const [answer, parts] = structuredClone(cur);
const num = parts.pop();
if (parts.length === 0 || num === undefined) {
return num === answer;
}
let nextAns = 0;
switch (operator) {
case 'add':
nextAns = answer - num;
if (nextAns < 0) {
return false;
}
break;
case 'mult':
nextAns = answer / num;
if (!Number.isInteger(nextAns)) {
return false;
}
break;
case 'concat': {
const ansStr = answer.toString();
const numStr = num.toString();
if (!ansStr.endsWith(numStr)) {
return false;
}
nextAns = Number(ansStr.slice(0, ansStr.lastIndexOf(numStr)));
break;
}
}
const next: I = [nextAns, parts];
return allowedOps.reduce(
(acc, o) => acc || doWork(next, o, allowedOps),
false,
);
}
function part1(input: Array<I>) {
let result: bigint = 0n;
for (let r of input) {
if (
doWork(r, 'mult', ['mult', 'add']) ||
doWork(r, 'add', ['mult', 'add'])
) {
result += BigInt(r[0]);
}
}
return result;
}
function part2(input: Array<I>) {
let result: bigint = 0n;
for (let r of input) {
if (
doWork(r, 'mult', ['mult', 'add', 'concat']) ||
doWork(r, 'concat', ['mult', 'add', 'concat']) ||
doWork(r, 'add', ['mult', 'add', 'concat'])
) {
result += BigInt(r[0]);
}
}
return result;
}
console.log(part1(myInputs));
console.log(part2(myInputs));