-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday01.ts
More file actions
62 lines (52 loc) · 1.27 KB
/
day01.ts
File metadata and controls
62 lines (52 loc) · 1.27 KB
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
import { readInput } from "./util.ts";
if (import.meta.main) {
const input = await readInput();
console.log("Part 1:", part1(input));
console.log("Part 2:", part2(input));
}
function toLists(input: string): [number[], number[]] {
const left: number[] = [],
right: number[] = [];
for (const line of input.split("\n")) {
const [l, r] = line.split(/\W+/);
left.push(Number(l)), right.push(Number(r));
}
return [left, right];
}
function part1(input: string): number {
const [left, right] = toLists(input);
left.sort(), right.sort();
return left.reduce((acc, l, i) => Math.abs(right[i] - l) + acc, 0);
}
function part2(input: string): number {
const [left, right] = toLists(input);
const counts = right.reduce<Record<number, number>>((acc, num) => {
if (num in acc) acc[num]++;
else acc[num] = 1;
return acc;
}, {});
return left.reduce(
(acc, val) => (val in counts ? acc + val * counts[val] : acc),
0
);
}
// Test
import { assertEquals } from "jsr:@std/assert@1.0.8";
Deno.test("Part 1: Total Distance", () => {
const out = part1(`3 4
4 3
2 5
1 3
3 9
3 3`);
assertEquals(out, 11);
});
Deno.test("Part 2: Similarity Score", () => {
const out = part2(`3 4
4 3
2 5
1 3
3 9
3 3`);
assertEquals(out, 31);
});