Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require("fs")
- const input = fs.readFileSync(__dirname + (process.argv.includes("--test") ? "/test.txt" : "/input.txt"), "utf8")
- let antennas, width, height
- function parseInput(rawInput) {
- const map = rawInput.split(/\r?\n/)
- antennas = []
- width = map[0].length
- height = map.length
- map.forEach((row, y) => {
- row.split("").forEach((char, x) => {
- if (char !== ".") antennas.push({ x, y, freq: char })
- })
- })
- }
- function calculateAntinodes(includeBetween = false) {
- const antinodes = new Set()
- for (const group of Object.values(groups)) {
- group.forEach(({ x, y }) => antinodes.add(`${x},${y}`))
- for (let i = 0; i < group.length; i++) {
- for (let j = i + 1; j < group.length; j++) {
- const { x: x1, y: y1 } = group[i]
- const { x: x2, y: y2 } = group[j]
- const dx = x2 - x1,
- dy = y2 - y1
- for (const dir of [-1, 1]) {
- let x = x1 + dir * dx
- let y = y1 + dir * dy
- while (x >= 0 && x < width && y >= 0 && y < height) {
- antinodes.add(`${x},${y}`)
- if (!includeBetween) break
- x += dir * dx
- y += dir * dy
- }
- }
- }
- }
- }
- return antinodes.size
- }
- let groups
- function part1() {
- parseInput(input)
- groups = antennas.reduce((acc, ant) => {
- ;(acc[ant.freq] ||= []).push(ant)
- return acc
- }, {})
- return calculateAntinodes(false)
- }
- function part2() {
- return calculateAntinodes(true)
- }
- console.time("Part 1 Time")
- console.log("Part 1:", part1())
- console.timeEnd("Part 1 Time")
- console.time("Part 2 Time")
- console.log("Part 2:", part2())
- console.timeEnd("Part 2 Time")
Advertisement
Add Comment
Please, Sign In to add comment