-
Notifications
You must be signed in to change notification settings - Fork 0
/
day11.rb
54 lines (47 loc) · 1.6 KB
/
day11.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
Monkey = Struct.new(:number, :items, :operation, :test, :iftrue, :iffalse)
monkeys = {}
File.read(ARGV[0]).lines.each_slice(7) do |chunk|
number = chunk[0].strip.match(/Monkey (\d*)\:/)[1].to_i
items = chunk[1].strip.split(':', 2)[1].split(',').map(&:to_i)
opstring = chunk[2].strip.split(':')[1].split('=')[1].strip.split(' ')
operation = nil
if opstring[1] == '*'
if opstring[2] == 'old'
operation = Proc.new { |x| x * x }
else
operation = Proc.new { |x| x * opstring[2].to_i }
end
elsif opstring[1] == '+'
operation = Proc.new { |x| x + opstring[2].to_i }
end
test = chunk[3].strip.match(/divisible by (\d*)/)[1].to_i
iftrue = chunk[4].strip.match(/throw to monkey (\d*)/)[1].to_i
iffalse = chunk[5].strip.match(/throw to monkey (\d*)/)[1].to_i
monkey = Monkey.new(number, items, operation, test, iftrue, iffalse)
monkeys[number] = monkey
end
# puts monkeys.inspect
inspects = Hash.new {|h,k| h[k] = 0}
def printmonkeys(monkeys)
monkeys.each do |num, monkey|
puts "#{num}: #{monkey[:items].inspect}"
end
end
for round in (1..20) do
monkeys.each do |num, monkey|
while monkey[:items].any?
inspects[num] += 1
item = monkey[:items].shift
level = monkey[:operation].call(item)
level = level / 3
if level % monkey[:test] == 0
monkeys[monkey[:iftrue]][:items] << level
# puts "#{num}: monkey #{monkey[:iftrue]} gets #{level}"
else
monkeys[monkey[:iffalse]][:items] << level
# puts "#{num}: monkey #{monkey[:iffalse]} gets #{level}"
end
end
end
end
puts inspects.values.max(2).reduce(:*)