-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday05.ts
74 lines (65 loc) · 2.43 KB
/
day05.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
import type { Day } from './Day.ts';
import { splitPairs } from './utils.ts';
export class DayImpl implements Day {
readonly input: { before: number[]; after: number[]; pageOrderingRules: string[]; updates: string[] };
constructor(input: string) {
this.input = this.parseInput(input);
}
parseInput(input: string) {
const [pageOrderingRules, updates] = input
.trim()
.split('\n\n')
.map((part: string) => {
return part
.split(/\n/);
});
const [before, after]: [number[], number[]] = splitPairs(pageOrderingRules.map(rule => rule.split('|').map(Number) as [number, number]));
return { pageOrderingRules, updates, before, after };
}
partOne() {
return this.input.updates
.map(u => u.split(',').map(Number))
.filter(u => updateIsValid(u, this.input.before, this.input.after))
.map(update => update[Math.ceil(update.length / 2) - 1])
.reduce((acc, val) => acc + val, 0);
}
partTwo() {
return this.input.updates
.map(u => u.split(',').map(Number))
.filter(u => !updateIsValid(u, this.input.before, this.input.after))
.map(u => reorderUpdate(u, this.input.before, this.input.after))
.map(update => update[Math.ceil(update.length / 2) - 1])
.reduce((acc, val) => acc + val, 0);
}
}
function updateIsValid(update: number[], before: number[], after: number[]) {
const result = update.filter((n, i) => {
const shouldBeBefore = getBefore(n, before, after);
if (shouldBeBefore.length === 0) {
return true;
}
const filteredBeforeNumber = shouldBeBefore.filter((beforeNumber) => {
const beforeIndexInUpdate = update.indexOf(beforeNumber);
return beforeIndexInUpdate < i;
});
return filteredBeforeNumber.length === shouldBeBefore.length;
});
return result.join(',') === update.join(',');
}
function getBefore(number: number, before: number[], after: number[]) {
const beforeIndexes = after.map((n, i) => n === number ? i : -1).filter(n => n >= 0);
return before.filter((_, i) => beforeIndexes.includes(i));
}
export function reorderUpdate(update: number[], before: number[], after: number[]): number[] {
return update.sort((a, b) => {
const shouldBeBeforeForA = getBefore(a, before, after);
const shouldBeBeforeForB = getBefore(b, before, after);
if (shouldBeBeforeForA.includes(b)) {
return 1;
}
if (shouldBeBeforeForB.includes(a)) {
return -1;
}
return 0;
});
}