mosredna

AoC 2024 day 8

Dec 8th, 2024 (edited)
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.91 KB | Source Code | 0 0
  1. const fs = require("fs")
  2.  
  3. const input = fs.readFileSync(__dirname + (process.argv.includes("--test") ? "/test.txt" : "/input.txt"), "utf8")
  4. let antennas, width, height
  5.  
  6. function parseInput(rawInput) {
  7.     const map = rawInput.split(/\r?\n/)
  8.     antennas = []
  9.     width = map[0].length
  10.     height = map.length
  11.  
  12.     map.forEach((row, y) => {
  13.         row.split("").forEach((char, x) => {
  14.             if (char !== ".") antennas.push({ x, y, freq: char })
  15.         })
  16.     })
  17. }
  18.  
  19. function calculateAntinodes(includeBetween = false) {
  20.     const antinodes = new Set()
  21.  
  22.     for (const group of Object.values(groups)) {
  23.         group.forEach(({ x, y }) => antinodes.add(`${x},${y}`))
  24.  
  25.         for (let i = 0; i < group.length; i++) {
  26.             for (let j = i + 1; j < group.length; j++) {
  27.                 const { x: x1, y: y1 } = group[i]
  28.                 const { x: x2, y: y2 } = group[j]
  29.                 const dx = x2 - x1,
  30.                     dy = y2 - y1
  31.  
  32.                 for (const dir of [-1, 1]) {
  33.                     let x = x1 + dir * dx
  34.                     let y = y1 + dir * dy
  35.  
  36.                     while (x >= 0 && x < width && y >= 0 && y < height) {
  37.                         antinodes.add(`${x},${y}`)
  38.                         if (!includeBetween) break
  39.                         x += dir * dx
  40.                         y += dir * dy
  41.                     }
  42.                 }
  43.             }
  44.         }
  45.     }
  46.  
  47.     return antinodes.size
  48. }
  49. let groups
  50. function part1() {
  51.     parseInput(input)
  52.  
  53.     groups = antennas.reduce((acc, ant) => {
  54.         ;(acc[ant.freq] ||= []).push(ant)
  55.         return acc
  56.     }, {})
  57.  
  58.     return calculateAntinodes(false)
  59. }
  60.  
  61. function part2() {
  62.     return calculateAntinodes(true)
  63. }
  64.  
  65. console.time("Part 1 Time")
  66. console.log("Part 1:", part1())
  67. console.timeEnd("Part 1 Time")
  68.  
  69. console.time("Part 2 Time")
  70. console.log("Part 2:", part2())
  71. console.timeEnd("Part 2 Time")
  72.  
Advertisement
Add Comment
Please, Sign In to add comment