You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
advent-of-code/2023/ruby/day_03.rb

63 lines
1.1 KiB

10 months ago
CurrentNumber = Data.define(:coords, :acc)
10 months ago
cur_num = nil
nums = {}
syms = {}
ARGF.readlines(chomp: true).each.with_index do |row, y|
row.chars.each.with_index do |c, x|
case c
when /\d/
if cur_num
10 months ago
cur_num.coords << [y,x]
cur_num.acc << c
10 months ago
else
10 months ago
cur_num = CurrentNumber.new([[y,x]], c)
10 months ago
end
else
if cur_num
10 months ago
nums.merge!(cur_num.coords.to_h { [_1, cur_num.acc.to_i] })
10 months ago
cur_num = nil
end
if c != ?.
syms[[y,x]] = c
end
end
end
if cur_num
10 months ago
nums.merge!(cur_num.coords.to_h { [_1, cur_num.acc.to_i] })
10 months ago
cur_num = nil
end
end
10 months ago
# part one
p syms
.flat_map {|(y,x), _|
10 months ago
dy = (-1..1).to_a
10 months ago
dx = (-1..1).to_a
dy.product(dx)
.map {|dy,dx| [y+dy,x+dx] }
.filter_map { nums.fetch(_1, nil) }
.uniq # lol, hack
}
.sum
p syms
.select { _2 == ?* }
.filter_map {|(y,x), _|
dy = (-1..1).to_a
dx = (-1..1).to_a
parts = dy.product(dx)
.map {|dy,dx| [y+dy,x+dx] }
.filter_map { nums.fetch(_1, nil) }
.uniq # lol, hack
if parts.length == 2
parts
10 months ago
else
nil
end
}
10 months ago
.sum { _1.inject(:*) }