aboutsummaryrefslogtreecommitdiff
path: root/day11/part2.rb
diff options
context:
space:
mode:
authorNat Lasseter <user@4574.co.uk>2022-12-11 12:53:22 +0000
committerNat Lasseter <user@4574.co.uk>2022-12-11 12:53:22 +0000
commitf1f4d07d5784d0bf2b63bd2206c7d5f5f7e76479 (patch)
tree7823590867edcf16ca9c13f111e642257cae1f3c /day11/part2.rb
parent1128a670513a77fa62cba789d5b4c942e3b46c5d (diff)
Day 11
Diffstat (limited to 'day11/part2.rb')
-rw-r--r--day11/part2.rb72
1 files changed, 72 insertions, 0 deletions
diff --git a/day11/part2.rb b/day11/part2.rb
new file mode 100644
index 0000000..0be5a5c
--- /dev/null
+++ b/day11/part2.rb
@@ -0,0 +1,72 @@
+class Monkey
+ def initialize(items, op, test, iftrue, iffalse)
+ @items = items
+ @op = op
+ @test = test
+ @iftrue = iftrue
+ @iffalse = iffalse
+ @inspections = 0
+ end
+
+ attr_reader :items, :inspections
+
+ def <<(item)
+ @items << item
+ end
+
+ def turn(wl)
+ @inspections += @items.count
+ ret = []
+ until @items.empty?
+ old = @items.shift
+ new = eval(@op) % wl
+ ret << [(new % @test == 0 ? @iftrue : @iffalse), new]
+ end
+ ret
+ end
+end
+
+class Game
+ def initialize
+ @monkeys = []
+ @worry_limit = 1
+ end
+
+ attr_accessor :worry_limit
+
+ def <<(monkey)
+ @monkeys << monkey
+ end
+
+ def round
+ @monkeys.each do |monkey|
+ monkey.turn(@worry_limit).each do |tom, val|
+ @monkeys[tom] << val
+ end
+ end
+ end
+
+ def inspections
+ @monkeys.map(&:inspections)
+ end
+end
+
+lines = $stdin.readlines.map(&:strip).reject(&:empty?)
+
+game = Game.new
+wl = 1
+lines.each_slice(6) do |mkls|
+ items = mkls[1].scan(/\d+/).map(&:to_i)
+ op = mkls[2].split(" = ")[1]
+ test = mkls[3].scan(/\d+/)[0].to_i
+ wl *= test
+ ift = mkls[4].scan(/\d+/)[0].to_i
+ iff = mkls[5].scan(/\d+/)[0].to_i
+ game << Monkey.new(items, op, test, ift, iff)
+end
+game.worry_limit = wl
+
+10_000.times do |i|
+ game.round
+end
+puts game.inspections.max(2).inject(&:*)