-
Notifications
You must be signed in to change notification settings - Fork 0
/
solver.ts
60 lines (53 loc) · 1.61 KB
/
solver.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
import { PuzzleSolver } from "../types/puzzle-solver.ts";
export default class Solver24D11 implements PuzzleSolver {
private initialStones: number[] = [];
parseInput(input: string[]) {
this.initialStones = input[0].split(" ").map(Number);
}
solvePart1() {
return this.blink(25);
}
solvePart2() {
return this.blink(75);
}
private blink(n: number) {
const frequencyMap = new Map<number, number>();
this.initialStones.forEach((stone) =>
alterMapValue(frequencyMap, stone, 1)
);
for (let i = 0; i < n; i++) {
for (const [stone, count] of [...frequencyMap]) {
alterMapValue(frequencyMap, stone, -count);
const resultStones = handleStone(stone);
resultStones.forEach((stone) =>
alterMapValue(frequencyMap, stone, count)
);
}
}
return frequencyMap.values().reduce((acc, count) => acc + count, 0);
}
}
function handleStone(stoneNumber: number) {
if (stoneNumber === 0) {
return [1];
}
const str = stoneNumber.toString();
if (str.length % 2 === 0) {
const left = Number(str.slice(0, str.length / 2));
const right = Number(str.slice(str.length / 2));
return [left, right];
}
return [stoneNumber * 2024];
}
function alterMapValue(
map: Map<number, number>,
key: number,
valueToAdd: number
) {
const newValue = (map.get(key) ?? 0) + valueToAdd;
if (newValue === 0) {
map.delete(key);
} else {
map.set(key, newValue);
}
}