-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
executable file
·85 lines (65 loc) · 2.14 KB
/
main.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
#!/usr/bin/env deno run --allow-read
import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
import { sum } from "../../2020/utils.ts";
export const DAYS_PART_ONE = 80;
export const DAYS_PART_TWO = 256;
export const BREED_DAYS = 7;
export const MATURE_DAYS = 8;
const parseInput = (string: string): number[] => {
return string.trim().split(",").map((s) => parseInt(s, 10));
};
const text = await Deno.readTextFile("input.txt");
export const input = parseInput(text);
const childrenDaysToBreed = (
daysToBreed: number,
daysToGo: number,
): number[] => {
const childNumbers = [];
for (let day = 1; day <= daysToGo; day++) {
if (daysToBreed === 0) {
daysToBreed = BREED_DAYS;
childNumbers.push(day + MATURE_DAYS);
}
daysToBreed--;
}
return childNumbers;
};
assertEquals(childrenDaysToBreed(3, 18), [12, 19, 26]);
assertEquals(childrenDaysToBreed(12, 18), [21]);
assertEquals(childrenDaysToBreed(1, 18), [10, 17, 24]);
assertEquals(childrenDaysToBreed(10, 18), [19, 26]);
assertEquals(childrenDaysToBreed(17, 18), [26]);
[19, 21, 24, 26].forEach((n) => {
assertEquals(childrenDaysToBreed(n, 18), []);
});
const memoize = <R>(func: (n: number) => R): (n: number) => R => {
const memory: Record<number, R> = {};
const memoizedFunc = (n: number): R => {
memory[n] ??= func(n);
return memory[n];
};
return memoizedFunc;
};
const unlimitedBreedCount = (
daysToBreeds: number[],
daysToGo: number,
): number => {
const getTotalSpawns = memoize((daysToBreed: number): number =>
1 + sum(
childrenDaysToBreed(daysToBreed, daysToGo).map(getTotalSpawns),
)
);
return sum(daysToBreeds.map(getTotalSpawns));
};
const part1 = (input: number[]): number => {
return unlimitedBreedCount(input, DAYS_PART_ONE);
};
export const example = parseInput(`3,4,3,1,2`);
assertEquals(unlimitedBreedCount(example, 18), 26);
assertEquals(part1(example), 5934);
console.log("Result part 1: " + part1(input));
const part2 = (input: number[]): number => {
return unlimitedBreedCount(input, DAYS_PART_TWO);
};
assertEquals(part2(example), 26984457539);
console.log("Result part 2: " + part2(input));