-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday11.ts
64 lines (56 loc) · 1.42 KB
/
day11.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
import type { Day } from './Day.ts';
export class DayImpl implements Day {
private readonly input: number[];
constructor(input: string) {
this.input = this.parseInput(input);
}
parseInput(input: string) {
return input
.trim()
.split(/\s+/)
.map(Number);
}
partOne() {
let count = 0;
const cache = new Map();
for (const num of this.input) {
count += blink(num, 0, 25, cache);
}
return count;
}
partTwo() {
let count = 0;
const cache = new Map<string, number>();
for (const num of this.input) {
count += blink(num, 0, 75, cache);
}
return count;
}
}
function blink(num: number, depth: number, target: number, cache: Map<string, number>): number {
const key = `${num}.${depth}`;
if (cache.has(key)) {
return cache.get(key)!;
}
let result: number = 0;
const nextDepth = depth + 1;
if (depth === target) {
result = 1;
}
else if (num === 0) {
result = blink(1, nextDepth, target, cache);
}
else {
const str = num.toString();
if (str.length % 2 === 0) {
const half = str.length / 2;
const [left, right] = [str.substring(0, half), str.substring(half, str.length)];
result = blink(Number(left), nextDepth, target, cache) + blink(Number(right), nextDepth, target, cache);
}
else {
result = blink(num * 2024, nextDepth, target, cache);
}
}
cache.set(key, result);
return result;
}