35 lines
845 B
JavaScript
Raw Normal View History

2024-12-02 10:50:22 +01:00
const fs = require("fs");
function parseInputAndCalculateDistance(filePath) {
const fileContent = fs.readFileSync(filePath, "utf-8");
const leftList = [];
const rightList = [];
fileContent.split("\n").forEach((line) => {
if (line.trim() !== "") {
const [left, right] = line.split(/\s+/).map(Number);
leftList.push(left);
rightList.push(right);
}
});
function calculateTotalDistance(left, right) {
left.sort((a, b) => a - b);
right.sort((a, b) => a - b);
let totalDistance = 0;
for (let i = 0; i < left.length; i++) {
totalDistance += Math.abs(left[i] - right[i]);
}
return totalDistance;
}
return calculateTotalDistance(leftList, rightList);
}
const filePath = "inputs/1";
const totalDistance = parseInputAndCalculateDistance(filePath);
console.log(totalDistance);