-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday9.ts
66 lines (50 loc) · 1.28 KB
/
day9.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
const test_input = `0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45`.split('\n');
const puzzle_input = `<get from aoc website>`.split('\n');
function log(u: unknown) {
console.log(JSON.stringify(u));
}
function numStringToArray(src: string): number[] {
return src
.split(' ')
.filter((s) => s.trim().length > 0)
.map(Number);
}
function part1(input: string[]) {
function nextRow(row: number[]): number {
if (row.every((i) => i === 0)) {
return 0;
}
const newRow: number[] = [];
for (let i = 1; i < row.length; i++) {
newRow.push(row[i] - row[i - 1]);
}
const add = nextRow(newRow);
return row[row.length - 1] + add;
}
const next = input.map((r) => {
const n = numStringToArray(r);
return nextRow(n);
});
log(next.reduce((a, c) => a + c));
}
function part2(input: string[]) {
function nextRow(row: number[]): number {
if (row.every((i) => i === 0)) {
return 0;
}
const newRow: number[] = [];
for (let i = 1; i < row.length; i++) {
newRow.push(row[i] - row[i - 1]);
}
const add = nextRow(newRow);
return row[0] - add;
}
const next = input.map((r) => {
const n = numStringToArray(r);
return nextRow(n);
});
log(next.reduce((a, c) => a + c));
}
part2(puzzle_input);