-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday05.ts
More file actions
108 lines (96 loc) · 1.83 KB
/
day05.ts
File metadata and controls
108 lines (96 loc) · 1.83 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
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 splitInput(input: string): [string, string[]] {
const [rules, updates] = input.split("\n\n");
return [rules, updates.split("\n")];
}
function sortUpdates(rules: string, updates: string[]) {
const sorter = (a: string, b: string) => {
if (a === b) return 0;
else if (rules.includes(`${a}|${b}`)) return -1;
else return 1;
};
return updates.map((update) => update.split(",").sort(sorter).join(","));
}
function sumMiddle(updates: string[]): number {
return updates.reduce((sum, update) => {
const nums = update.split(",");
return sum + Number(nums[Math.floor(nums.length / 2)]);
}, 0);
}
function part1(input: string): number {
const [rules, updates] = splitInput(input);
const sorted = sortUpdates(rules, updates);
return sumMiddle(sorted.filter((update) => updates.includes(update)));
}
function part2(input: string): number {
const [rules, updates] = splitInput(input);
const sorted = sortUpdates(rules, updates);
return sumMiddle(sorted.filter((update) => !updates.includes(update)));
}
// Test
import { assertEquals } from "jsr:@std/assert@1.0.8";
Deno.test("Part 1: ", () => {
const out = part1(`47|53
97|13
97|61
97|47
75|29
61|13
75|53
29|13
97|29
53|29
61|53
97|53
61|29
47|13
75|47
97|75
47|61
75|61
47|29
75|13
53|13
75,47,61,53,29
97,61,53,29,13
75,29,13
75,97,47,61,53
61,13,29
97,13,75,29,47`);
assertEquals(out, 143);
});
Deno.test("Part 2: ", () => {
const out = part2(`47|53
97|13
97|61
97|47
75|29
61|13
75|53
29|13
97|29
53|29
61|53
97|53
61|29
47|13
75|47
97|75
47|61
75|61
47|29
75|13
53|13
75,47,61,53,29
97,61,53,29,13
75,29,13
75,97,47,61,53
61,13,29
97,13,75,29,47`);
assertEquals(out, 123);
});