[2023][ruby][3.2]

main
Alpha Chen 11 months ago
parent 6581325e8f
commit fc5821b277
Signed by: alpha
SSH Key Fingerprint: SHA256:3fOT8fiYQG/aK9ntivV3Bqtg8AYQ7q4nV6ZgihOA20g

@ -1,3 +1,5 @@
CurrentNumber = Data.define(:coords, :acc)
cur_num = nil cur_num = nil
nums = {} nums = {}
syms = {} syms = {}
@ -6,13 +8,14 @@ ARGF.readlines(chomp: true).each.with_index do |row, y|
case c case c
when /\d/ when /\d/
if cur_num if cur_num
cur_num << c cur_num.coords << [y,x]
cur_num.acc << c
else else
cur_num = c cur_num = CurrentNumber.new([[y,x]], c)
end end
else else
if cur_num if cur_num
nums[[y,x-cur_num.length]] = cur_num.to_i nums.merge!(cur_num.coords.to_h { [_1, cur_num.acc.to_i] })
cur_num = nil cur_num = nil
end end
@ -23,21 +26,37 @@ ARGF.readlines(chomp: true).each.with_index do |row, y|
end end
if cur_num if cur_num
nums[[y, row.length-cur_num.length]] = cur_num.to_i nums.merge!(cur_num.coords.to_h { [_1, cur_num.acc.to_i] })
cur_num = nil cur_num = nil
end end
end end
p nums # part one
.filter_map {|(y,x), num| p syms
.flat_map {|(y,x), _|
dy = (-1..1).to_a
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 dy = (-1..1).to_a
dx = (-1..num.digits.length).to_a dx = (-1..1).to_a
if dy.product(dx) parts = dy.product(dx)
.map {|dy,dx| [y+dy,x+dx] } .map {|dy,dx| [y+dy,x+dx] }
.any? { syms.has_key?(_1) } .filter_map { nums.fetch(_1, nil) }
num .uniq # lol, hack
if parts.length == 2
parts
else else
nil nil
end end
} }
.sum .sum { _1.inject(:*) }

Loading…
Cancel
Save