mosredna

AoC 2024 day 3

Dec 2nd, 2024 (edited)
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.12 KB | Source Code | 0 0
  1. // Advent of Code 2024 - Day 3
  2. const fs = require("fs")
  3.  
  4. const input = fs.readFileSync(__dirname + (process.argv.includes("--test") ? "/test.txt" : "/input.txt"), "utf8")
  5.  
  6. const parseInput = (rawInput) => {
  7.     return rawInput.split("\n")
  8. }
  9.  
  10. const part1 = (str) => {
  11.     const regex = /mul\((\d{1,3}),(\d{1,3})\)/g
  12.  
  13.     let sum = 0
  14.     let match
  15.  
  16.     while ((match = regex.exec(str)) !== null) {
  17.         sum += parseInt(match[1]) * parseInt(match[2])
  18.     }
  19.  
  20.     return sum
  21. }
  22.  
  23. const part2 = (str) => {
  24.     const regex = /do\(\)|don't\(\)|mul\((\d{1,3}),(\d{1,3})\)/g
  25.  
  26.     let enabled = true
  27.     let sum = 0
  28.     let match
  29.  
  30.     while ((match = regex.exec(str)) !== null) {
  31.         if (match[0] === "do()") enabled = true
  32.         else if (match[0] === "don't()") enabled = false
  33.         else if (enabled) sum += parseInt(match[1]) * parseInt(match[2])
  34.     }
  35.  
  36.     return sum
  37. }
  38.  
  39. const data = parseInput(input)
  40.  
  41. console.time("Part 1 Time")
  42. console.log("Part 1:", part1(data))
  43. console.timeEnd("Part 1 Time")
  44.  
  45. console.time("Part 2 Time")
  46. console.log("Part 2:", part2(data))
  47. console.timeEnd("Part 2 Time")
  48.  
Advertisement
Add Comment
Please, Sign In to add comment