diff --git a/2023/ruby/day_15.rb b/2023/ruby/day_15.rb index 24bc487..01c73d4 100644 --- a/2023/ruby/day_15.rb +++ b/2023/ruby/day_15.rb @@ -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 -p input.sum {|str| - current = 0 - str.each do |c| - current += c.ord - current *= 17 - current %= 256 +p input.split(?,).sum { hash(_1) } + +# part two +boxes = Hash.new {|h,k| h[k] = {} } +input.scan(/(\w+)([-=])(\d+)?/).each do |label, op, focal_length| + box = boxes[hash(label)] + case op + when ?- + box.delete(label) + when ?= + box[label] = focal_length.to_i + else + fail end - current -} +end + +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