Last active
December 3, 2023 19:12
-
-
Save henrik/1b5435841d97b9448bd603d8c38da067 to your computer and use it in GitHub Desktop.
Advent of Code day 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
grid = DATA.readlines.map(&:chomp) | |
max_line = grid.length - 1 | |
max_col = grid.first.length - 1 | |
sum = 0 | |
grid.each_with_index do |line, i| | |
tokens = line.scan(/(\D*)(\d+)/).flatten | |
offset = 0 | |
tokens.each.with_index do |token, j| | |
is_number = j.odd? | |
if is_number | |
left = [ offset - 1, 0 ].max | |
right = [ offset + token.length, max_col ].min | |
over = [ i - 1 , 0 ].max | |
under = [ i + 1, max_line ].min | |
neighbours = "" | |
neighbours += grid[over][left..right] | |
neighbours += grid[i][left..right] | |
neighbours += grid[under][left..right] | |
sum += token.to_i if neighbours.match?(/[^\d.]/) | |
end | |
offset += token.length | |
end | |
end | |
puts sum | |
__END__ | |
Data goes here |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
grid = DATA.readlines.map(&:chomp) | |
max_line = grid.length - 1 | |
max_col = grid.first.length - 1 | |
gears_to_numbers = Hash.new { |h, k| h[k] = [] } | |
grid.each_with_index do |line, i| | |
tokens = line.scan(/(\D*)(\d+)/).flatten | |
offset = 0 | |
tokens.each.with_index do |token, j| | |
is_number = j.odd? | |
if is_number | |
left = [ offset - 1, 0 ].max | |
right = [ offset + token.length, max_col ].min | |
over = [ i - 1 , 0 ].max | |
under = [ i + 1, max_line ].min | |
[ over, i, under ].uniq.each do |row| | |
grid[row][left..right].each_char.with_index(left).each do |c, k| | |
next unless c == "*" | |
gears_to_numbers[[row, k]] << token.to_i | |
end | |
end | |
end | |
offset += token.length | |
end | |
end | |
puts gears_to_numbers.values.reject { _1.length == 1 }.sum { _1.reduce(:*) } | |
__END__ | |
Data goes here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment