1
0
Fork 0
advent-of-code-2024/08/8-2.rb

93 lines
1.8 KiB
Ruby
Raw Normal View History

2024-12-08 19:20:48 -05:00
#!/usr/bin/env ruby
problem = 8
input = File.readlines("#{problem}.input").map(&:strip)
#input = DATA.read.split("\n")
# Find diferent antennas
signals = input.join.chars.uniq
.reject { _1 == "." }
.map { [_1, []] }
.to_h
grid = input.map(&:chars)
# map antenna locations
signals.keys.each do |signal|
grid.each_with_index do |row, x|
row.each_with_index do |val, y|
signals[val] << [x, y] if val == signal
end
end
end
# calculate antinodes between all node pairs
antinodes = []
signals.each do |(signal, locations)|
locations.each { antinodes << _1 }
locations.combination(2).each do |(first, second)|
x = (first.first - second.first).abs
y = (first.last - second.last).abs
node1, node2 = first, second
loop do
if first.first < second.first
x1 = node1.first - x
else
x1 = node1.first + x
end
if first.last < second.last
y1 = node1.last - y
else
y1 = node1.last + y
end
node1 = [x1, y1]
break unless x1 >= 0 && y1 >= 0 && x1 < grid.size && y1 < grid.first.size
antinodes << node1
end
loop do
if first.first < second.first
x2 = node2.first + x
else
x2 = node2.first - x
end
if first.last < second.last
y2 = node2.last + y
else
y2 = node2.last - y
end
node2 = [x2, y2]
break unless x2 >= 0 && y2 >= 0 && x2 < grid.size && y2 < grid.first.size
antinodes << node2
end
end
end
p antinodes.uniq.size
grid.each_with_index do |row, x|
row.each_with_index do |val, y|
if antinodes.index([x,y])
print "#"
else
print grid[x][y]
end
end
puts
end
__END__
............
........0...
.....0......
.......0....
....0.......
......A.....
............
............
........A...
.........A..
............
............