This commit is contained in:
2024-01-10 00:45:16 -05:00
parent c5309e9de3
commit c8a3a0074b
2 changed files with 94 additions and 0 deletions

46
2023/day11/p1.rb Normal file
View File

@@ -0,0 +1,46 @@
# frozen_string_literal: true
def build_space_arr(grid)
offset = []
grid.each_with_index do |row, i|
offset << if row.include? '#'
if offset.empty?
0
else
offset[i - 1] + 1
end
elsif offset.empty?
1
else
offset[i - 1] + 2
end
end
offset
end
res = 0
grid = []
File.foreach('./2023/day11/data') do |line|
grid << line.strip.split('')
end
row_offset = build_space_arr grid
col_offset = build_space_arr grid.transpose
found_galaxies = []
grid.each_with_index do |row, r|
row.each_with_index do |char, c|
next unless char == '#'
found_galaxies.each do |galaxy|
res += (row_offset[r] - galaxy[:x]).abs + (col_offset[c] - galaxy[:y]).abs
end
found_galaxies << {
x: row_offset[r],
y: col_offset[c]
}
end
end
puts res

48
2023/day11/p2.rb Normal file
View File

@@ -0,0 +1,48 @@
# frozen_string_literal: true
# This is actually identical to p1, except for the offset of + 1_000_000 which was previously + 2
def build_space_arr(grid)
offset = []
grid.each_with_index do |row, i|
offset << if row.include? '#'
if offset.empty?
0
else
offset[i - 1] + 1
end
elsif offset.empty?
1
else
offset[i - 1] + 1_000_000
end
end
offset
end
res = 0
grid = []
File.foreach('./2023/day11/data') do |line|
grid << line.strip.split('')
end
row_offset = build_space_arr grid
col_offset = build_space_arr grid.transpose
found_galaxies = []
grid.each_with_index do |row, r|
row.each_with_index do |char, c|
next unless char == '#'
found_galaxies.each do |galaxy|
res += (row_offset[r] - galaxy[:x]).abs + (col_offset[c] - galaxy[:y]).abs
end
found_galaxies << {
x: row_offset[r],
y: col_offset[c]
}
end
end
puts res