Files
AoC/2024/01/index.ts

47 lines
783 B
TypeScript
Raw Normal View History

2024-12-01 23:13:46 +00:00
const fs = require('fs');
const input = fs.readFileSync(__dirname + '/input.txt', 'utf8');
const arr1: Array<number> = [];
const arr2: Array<number> = [];
input.split("\n").forEach((n: string) => {
if (n.match('^\s*$')) {
return;
}
const ns = n.split(' ');
arr1.push(parseInt(ns[0]));
arr2.push(parseInt(ns[1]));
});
// Part 1
2024-12-02 23:37:11 +00:00
arr1.sort();
arr2.sort();
2024-12-01 23:13:46 +00:00
2024-12-02 23:37:11 +00:00
let sum = 0;
2024-12-01 23:13:46 +00:00
2024-12-02 23:37:11 +00:00
arr1.forEach((v, k) => {
sum += Math.max(v, arr2[k]) - Math.min(v, arr2[k]);
});
2024-12-01 23:13:46 +00:00
2024-12-02 23:37:11 +00:00
console.log(sum);
2024-12-01 23:13:46 +00:00
2024-12-02 23:37:11 +00:00
// Part 2
2024-12-01 23:13:46 +00:00
const map: { [key: number]: number } = {};
arr2.forEach((v) => {
if (typeof map[v] === 'undefined') {
map[v] = 1;
} else {
map[v]++;
}
});
let score = 0;
arr1.forEach((v) => {
score += (v * (map[v] || 0));
});
console.log(score);