parent
5bbeb5d969
commit
10da9e80a0
@ -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
|
||||
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…
Reference in new issue