mosredna

AoC 2024 day 1

Dec 1st, 2024 (edited)
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.19 KB | Source Code | 0 0
  1. // Advent of Code 2024 - Day 1
  2. const fs = require("fs")
  3.  
  4. // Read input
  5. const input = fs.readFileSync(__dirname + (process.argv.includes("--test") ? "/test.txt" : "/input.txt"), "utf8")
  6.  
  7. // Parse input
  8. const parseInput = (rawInput) => rawInput.split("\n").map((line) => line.split("   ").map(Number))
  9.  
  10. // Part 1: Calculate total absolute difference
  11. const part1 = (data) => {
  12.     const [left, right] = [
  13.         data.map((row) => row[0]).sort((a, b) => a - b),
  14.         data.map((row) => row[1]).sort((a, b) => a - b)
  15.     ]
  16.  
  17.     return left.reduce((sum, value, index) => sum + Math.abs(value - right[index]), 0)
  18. }
  19.  
  20. // Part 2: Calculate weighted total using occurrences
  21. const part2 = (data) => {
  22.     const left = data.map((row) => row[0])
  23.     const rightOccurrences = data.reduce((map, val) => map.set(val[1], (map.get(val[1]) || 0) + 1), new Map())
  24.  
  25.     return left.reduce((sum, val) => sum + val * (rightOccurrences.get(val) || 0), 0)
  26. }
  27.  
  28. // Run both parts
  29. const data = parseInput(input)
  30.  
  31. console.time("Part 1 Time")
  32. console.log("Part 1:", part1(data))
  33. console.timeEnd("Part 1 Time")
  34.  
  35. console.time("Part 2 Time")
  36. console.log("Part 2:", part2(data))
  37. console.timeEnd("Part 2 Time")
  38.  
Advertisement
Add Comment
Please, Sign In to add comment