-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
81 lines (65 loc) · 1.79 KB
/
index.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
import {
INPUT_PATH,
runner,
SAMPLE_PATH,
splitLines,
} from '../../../lib/utils';
const path = `${__dirname}/${INPUT_PATH}`;
const cache = new Map<number, number[]>();
const blink = (values: Map<number, number>) => {
const nextValues = new Map<number, number>();
for (const [el, count] of values.entries()) {
const cacheItem = cache.get(el);
if (cacheItem) {
nextValues.set(cacheItem[0], (nextValues.get(cacheItem[0]) || 0) + count);
if (cacheItem[1] >= 0) {
nextValues.set(
cacheItem[1],
(nextValues.get(cacheItem[1]) || 0) + count,
);
}
continue;
}
if (el === 0) {
nextValues.set(1, (nextValues.get(1) || 0) + count);
cache.set(el, [1]);
continue;
}
const elStrLen = el.toString().length;
if (elStrLen % 2 === 0) {
const half = elStrLen / 2;
const divider = 10 ** half;
const left = Math.floor(el / divider);
const right = el % divider;
nextValues.set(left, (nextValues.get(left) || 0) + count);
nextValues.set(right, (nextValues.get(right) || 0) + count);
cache.set(el, [left, right]);
} else {
const newVal = el * 2024;
nextValues.set(newVal, (nextValues.get(newVal) || 0) + count);
cache.set(el, [newVal]);
}
}
return nextValues;
};
const p1 = (input: string, limit: number) => {
const lines = input.split(' ').map(Number);
let stoneCache = new Map<number, number>();
for (const i of lines) stoneCache.set(i, 1);
for (let i = 0; i < limit; i++) {
stoneCache = blink(stoneCache);
}
return stoneCache.entries().reduce((acc, [, val]) => acc + val, 0);
};
runner({
path,
solution: (input) => {
return p1(input, 25);
},
});
runner({
path,
solution: (input) => {
return p1(input, 75);
},
});