-
Notifications
You must be signed in to change notification settings - Fork 0
/
day1.ts
45 lines (33 loc) · 909 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
import { readFileSync } from "node:fs";
const list1: number[] = [];
const list2: number[] = [];
try {
const data = readFileSync('day1.txt', 'utf8');
data.split('\n').forEach((line) => {
const [n1, n2] = line.split(' ').map(Number);
if (n1) {
list1.push(n1);
}
if (n2) {
list2.push(n2);
}
});
list1.sort((a, b) => a - b);
list2.sort((a, b) => a - b);
let totalDistance = 0;
const limit = Math.min(list1.length, list2.length);
for (let i = 0; i < limit; i++) {
totalDistance += Math.abs(list1[i] - list2[i]);
}
const map = new Map();
for (let i = 0; i < limit; i++) {
map.set(list2[i], (map.get(list2[i]) ?? 0) + 1);
}
let similarityScore = 0;
for (let i = 0; i < limit; i++) {
similarityScore += list1[i] * (map.get(list1[i]) ?? 0);
}
console.log(totalDistance, similarityScore);
} catch (err) {
console.error(err);
}