Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Advent of Code 2024 - Day 7
- const fs = require("fs")
- // Load and parse the input
- const input = fs.readFileSync(__dirname + (process.argv.includes("--test") ? "/test.txt" : "/input.txt"), "utf8")
- const parseInput = (rawInput) =>
- rawInput.split(/\r?\n/).map((line) => {
- const [testValue, numbers] = line.split(":")
- return {
- testValue: Number(testValue),
- numbers: numbers.trim().split(" ").map(Number)
- }
- })
- const evaluateExpression = (numbers, operators) =>
- operators.reduce((result, op, i) => {
- const next = numbers[i + 1]
- if (op === "+") return result + next
- if (op === "*") return result * next
- if (op === "||") return Number(result + "" + next)
- return result
- }, numbers[0])
- const generateOperators = (length, allowConcat) => {
- const operators = allowConcat ? ["+", "*", "||"] : ["+", "*"]
- return length === 0
- ? [[]]
- : generateOperators(length - 1, allowConcat).flatMap((combo) => operators.map((op) => [op, ...combo]))
- }
- const solve = (data, allowConcat) => {
- const operatorCombosCache = new Map()
- return data.reduce((total, { testValue, numbers }) => {
- const key = numbers.length - 1
- if (!operatorCombosCache.has(key)) {
- operatorCombosCache.set(key, generateOperators(key, allowConcat))
- }
- const operatorCombos = operatorCombosCache.get(key)
- const isSolvable = operatorCombos.some((operators) => evaluateExpression(numbers, operators) === testValue)
- return total + (isSolvable ? testValue : 0)
- }, 0)
- }
- const data = parseInput(input)
- console.time("Part 1 Time")
- console.log("Part 1:", solve(data, false))
- console.timeEnd("Part 1 Time")
- console.time("Part 2 Time")
- console.log("Part 2:", solve(data, true))
- console.timeEnd("Part 2 Time")
Advertisement
Add Comment
Please, Sign In to add comment