Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Advent of Code 2024 - Day 1
- const fs = require("fs")
- // Read input
- const input = fs.readFileSync(__dirname + (process.argv.includes("--test") ? "/test.txt" : "/input.txt"), "utf8")
- // Parse input
- const parseInput = (rawInput) => rawInput.split("\n").map((line) => line.split(" ").map(Number))
- // Part 1: Calculate total absolute difference
- const part1 = (data) => {
- const [left, right] = [
- data.map((row) => row[0]).sort((a, b) => a - b),
- data.map((row) => row[1]).sort((a, b) => a - b)
- ]
- return left.reduce((sum, value, index) => sum + Math.abs(value - right[index]), 0)
- }
- // Part 2: Calculate weighted total using occurrences
- const part2 = (data) => {
- const left = data.map((row) => row[0])
- const rightOccurrences = data.reduce((map, val) => map.set(val[1], (map.get(val[1]) || 0) + 1), new Map())
- return left.reduce((sum, val) => sum + val * (rightOccurrences.get(val) || 0), 0)
- }
- // Run both parts
- const data = parseInput(input)
- console.time("Part 1 Time")
- console.log("Part 1:", part1(data))
- console.timeEnd("Part 1 Time")
- console.time("Part 2 Time")
- console.log("Part 2:", part2(data))
- console.timeEnd("Part 2 Time")
Advertisement
Add Comment
Please, Sign In to add comment