-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday9.ts
65 lines (55 loc) · 1.8 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
import { assertEquals } from "https://deno.land/std@0.208.0/assert/mod.ts";
import { loadTestData, loadData } from "./utils.ts";
const part1test = 114;
const part2test = 2;
const part1 = (data: string) => {
const histories = data
.split('\n')
.map(line => line
.split(" ")
.map(n => parseInt(n)));
let sum = 0;
for (const history of histories) {
const diffs = [history];
while (diffs[diffs.length - 1].filter(x => x != 0).length > 0) {
const last = diffs[diffs.length - 1];
const newDiffs = [];
for (let i = 1; i < last.length; i++) {
newDiffs.push(last[i] - last[i - 1]);
}
diffs.push(newDiffs);
}
const lasts = diffs.map(diff => diff[diff.length - 1]);
sum += lasts.reduce((a, b) => a + b);
}
return sum;
};
const part2 = (data: string) => {
const histories = data
.split('\n')
.map(line => line
.split(" ")
.map(n => parseInt(n)));
let sum = 0;
for (const history of histories) {
const diffs = [history];
while (diffs[diffs.length - 1].filter(x => x != 0).length > 0) {
const last = diffs[diffs.length - 1];
const newDiffs = [];
for (let i = 1; i < last.length; i++) {
newDiffs.push(last[i] - last[i - 1]);
}
diffs.push(newDiffs);
}
let extrap = 0;
for (let i = diffs.length - 2; i >= 0; i--) {
extrap = diffs[i][0] - extrap;
}
sum += extrap
}
return sum;
};
assertEquals(part1(await loadTestData(9)), part1test)
console.log(part1(await loadData(9)))
assertEquals(part2(await loadTestData(9)), part2test)
console.log(part2(await loadData(9)))