Files
AoC/2024/01/index.ts
2024-12-02 23:37:11 +00:00

47 lines
783 B
TypeScript

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
arr1.sort();
arr2.sort();
let sum = 0;
arr1.forEach((v, k) => {
sum += Math.max(v, arr2[k]) - Math.min(v, arr2[k]);
});
console.log(sum);
// Part 2
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);