Advertisement
Guest User

AOC 2024 Day 08

a guest
Dec 8th, 2024
53
0
151 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Julia 1.71 KB | None | 0 0
  1. testGrid = stack(readlines("day08/test.txt"); dims=1)
  2. grid = stack(readlines("day08/input.txt"); dims=1)
  3.  
  4. isAntenna(c) = c != '.'
  5. printMat(m) = println(join((join(m[i,:]) for i in axes(m,1)), "\n"))
  6. getPairs(x) = (Pair(x[i], x[j]) for i = eachindex(x) for j = i:length(x) if i != j)
  7.  
  8. function solve(grid, p2)
  9.     antIdx = findall(isAntenna.(grid))
  10.     antennas = unique(grid[antIdx])
  11.     antiNodes = Set()
  12.  
  13.     for ant ∈ antennas
  14.         idx = antIdx[grid[antIdx] .== ant]
  15.  
  16.         for p ∈ getPairs(idx)
  17.             slope = p.second - p.first
  18.             if p2
  19.                 for op ∈ [+, -] # Forwards and backwards
  20.                     n = 0
  21.                     point = op(p.first, slope*n)
  22.                     while checkbounds(Bool, grid, point)
  23.                         push!(antiNodes, point)
  24.                         n += 1
  25.                         point = op(p.first, slope*n)
  26.                     end
  27.                 end
  28.             else
  29.                 a1 = p.first - slope
  30.                 if checkbounds(Bool, grid, a1)
  31.                     push!(antiNodes, a1)
  32.                 end
  33.                 a2 = p.second + slope
  34.                 if checkbounds(Bool, grid, a2)
  35.                     push!(antiNodes, a2)
  36.                 end
  37.             end
  38.         end
  39.     end
  40.     return antiNodes
  41. end
  42.  
  43. function showAns(grid, nodes)
  44.     grid = copy(grid)
  45.     for node ∈ nodes
  46.         if !isAntenna(grid[node])
  47.             grid[node] = '#'
  48.         end
  49.     end
  50.     printMat(grid)
  51. end
  52.  
  53. @time nodes = solve(grid, false)
  54. # showAns(grid,nodes)
  55. println("P1 anti-node count: $(length(nodes))")
  56.  
  57. @time nodes = solve(grid, true)
  58. # showAns(grid,nodes)
  59. println("P2 anti-node count: $(length(nodes))")
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement