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_15.rb

31 lines
551 B

12 months ago
input = ARGF.read
def hash(label)
label.chars.inject(0) {|n,c|
(n + c.ord) * 17 % 256
}
end
12 months ago
# part one
12 months ago
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
12 months ago
end
12 months ago
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