Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Advent of Code 2024 - Day 2
- const fs = require("fs")
- const input = fs.readFileSync(__dirname + (process.argv.includes("--test") ? "/test.txt" : "/input.txt"), "utf8").trim()
- const data = input.split("\n").map((r) => r.split(" ").map(Number))
- // Check if a report is safe
- const isReportSafe = (report) => {
- const diffs = report.slice(1).map((level, i) => level - report[i])
- const isIncreasing = diffs[0] > 0
- return diffs.every((diff) => Math.abs(diff) >= 1 && Math.abs(diff) <= 3 && diff > 0 === isIncreasing)
- }
- // Check if removing one level makes the report safe
- const isSafeWithOneRemoval = (report) =>
- report.some((_, i) => isReportSafe(report.slice(0, i).concat(report.slice(i + 1))))
- // Part 1: Count reports that are directly safe
- const part1 = (data) => data.filter(isReportSafe).length
- // Part 2: Count reports that are safe or can be made safe by removing one level
- const part2 = (data) => data.filter((report) => isReportSafe(report) || isSafeWithOneRemoval(report)).length
- 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