[2023][ruby][15.2]

main
Alpha Chen 12 months ago
parent 5bbeb5d969
commit 10da9e80a0
Signed by: alpha
SSH Key Fingerprint: SHA256:3fOT8fiYQG/aK9ntivV3Bqtg8AYQ7q4nV6ZgihOA20g

@ -1,12 +1,30 @@
input = ARGF.read.strip.split(?,).map(&:chars) input = ARGF.read
def hash(label)
label.chars.inject(0) {|n,c|
(n + c.ord) * 17 % 256
}
end
# part one # part one
p input.sum {|str| p input.split(?,).sum { hash(_1) }
current = 0
str.each do |c| # part two
current += c.ord boxes = Hash.new {|h,k| h[k] = {} }
current *= 17 input.scan(/(\w+)([-=])(\d+)?/).each do |label, op, focal_length|
current %= 256 box = boxes[hash(label)]
case op
when ?-
box.delete(label)
when ?=
box[label] = focal_length.to_i
else
fail
end
end end
current
p boxes.flat_map {|box_i, box|
box.map.with_index {|(label, focal_length), lens_i|
[1 + box_i, 1 + lens_i, focal_length].inject(:*)
} }
}.sum

Loading…
Cancel
Save