mosredna

AoC 2024 day 7

Dec 7th, 2024
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.86 KB | Source Code | 0 0
  1. // Advent of Code 2024 - Day 7
  2. const fs = require("fs")
  3.  
  4. // Load and parse the input
  5. const input = fs.readFileSync(__dirname + (process.argv.includes("--test") ? "/test.txt" : "/input.txt"), "utf8")
  6.  
  7. const parseInput = (rawInput) =>
  8.     rawInput.split(/\r?\n/).map((line) => {
  9.         const [testValue, numbers] = line.split(":")
  10.         return {
  11.             testValue: Number(testValue),
  12.             numbers: numbers.trim().split(" ").map(Number)
  13.         }
  14.     })
  15.  
  16. const evaluateExpression = (numbers, operators) =>
  17.     operators.reduce((result, op, i) => {
  18.         const next = numbers[i + 1]
  19.         if (op === "+") return result + next
  20.         if (op === "*") return result * next
  21.         if (op === "||") return Number(result + "" + next)
  22.         return result
  23.     }, numbers[0])
  24.  
  25. const generateOperators = (length, allowConcat) => {
  26.     const operators = allowConcat ? ["+", "*", "||"] : ["+", "*"]
  27.     return length === 0
  28.         ? [[]]
  29.         : generateOperators(length - 1, allowConcat).flatMap((combo) => operators.map((op) => [op, ...combo]))
  30. }
  31.  
  32. const solve = (data, allowConcat) => {
  33.     const operatorCombosCache = new Map()
  34.     return data.reduce((total, { testValue, numbers }) => {
  35.         const key = numbers.length - 1
  36.         if (!operatorCombosCache.has(key)) {
  37.             operatorCombosCache.set(key, generateOperators(key, allowConcat))
  38.         }
  39.  
  40.         const operatorCombos = operatorCombosCache.get(key)
  41.         const isSolvable = operatorCombos.some((operators) => evaluateExpression(numbers, operators) === testValue)
  42.  
  43.         return total + (isSolvable ? testValue : 0)
  44.     }, 0)
  45. }
  46.  
  47. const data = parseInput(input)
  48.  
  49. console.time("Part 1 Time")
  50. console.log("Part 1:", solve(data, false))
  51. console.timeEnd("Part 1 Time")
  52.  
  53. console.time("Part 2 Time")
  54. console.log("Part 2:", solve(data, true))
  55. console.timeEnd("Part 2 Time")
  56.  
Advertisement
Add Comment
Please, Sign In to add comment