-
Notifications
You must be signed in to change notification settings - Fork 0
/
day1.ts
45 lines (33 loc) · 911 Bytes
/
day1.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
import { input } from './input';
const left: number[] = [];
const right: number[] = [];
input.split('\n').forEach((line) => {
const [l, r] = line.split('\t');
left.push(Number.parseInt(l));
right.push(Number.parseInt(r));
});
function part1(left: number[], right: number[]) {
const sort = (x: number, y: number) => x - y;
left.sort(sort);
right.sort(sort);
let result: bigint = 0n;
for (let i = 0; i < left.length; i++) {
result += BigInt(Math.abs(left[i] - right[i]));
}
return result;
}
function part2(left: number[], right: number[]) {
const map = new Map<number, number>();
for (let n of right) {
const cnt = (map.get(n) ?? 0) + 1;
map.set(n, cnt);
}
let result: bigint = 0n;
for (let n of left) {
const mult = map.get(n) ?? 0;
result += BigInt(n * mult);
}
return result;
}
console.log(part1(left, right));
console.log(part2(left, right));