mosredna

AoC 2024 day 2

Dec 2nd, 2024 (edited)
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.20 KB | Source Code | 0 0
  1. // Advent of Code 2024 - Day 2
  2. const fs = require("fs")
  3.  
  4. const input = fs.readFileSync(__dirname + (process.argv.includes("--test") ? "/test.txt" : "/input.txt"), "utf8").trim()
  5. const data = input.split("\n").map((r) => r.split(" ").map(Number))
  6.  
  7. // Check if a report is safe
  8. const isReportSafe = (report) => {
  9.     const diffs = report.slice(1).map((level, i) => level - report[i])
  10.     const isIncreasing = diffs[0] > 0
  11.  
  12.     return diffs.every((diff) => Math.abs(diff) >= 1 && Math.abs(diff) <= 3 && diff > 0 === isIncreasing)
  13. }
  14.  
  15. // Check if removing one level makes the report safe
  16. const isSafeWithOneRemoval = (report) =>
  17.     report.some((_, i) => isReportSafe(report.slice(0, i).concat(report.slice(i + 1))))
  18.  
  19. // Part 1: Count reports that are directly safe
  20. const part1 = (data) => data.filter(isReportSafe).length
  21.  
  22. // Part 2: Count reports that are safe or can be made safe by removing one level
  23. const part2 = (data) => data.filter((report) => isReportSafe(report) || isSafeWithOneRemoval(report)).length
  24.  
  25. console.time("Part 1 Time")
  26. console.log("Part 1:", part1(data))
  27. console.timeEnd("Part 1 Time")
  28.  
  29. console.time("Part 2 Time")
  30. console.log("Part 2:", part2(data))
  31. console.timeEnd("Part 2 Time")
  32.  
Advertisement
Add Comment
Please, Sign In to add comment