aboutsummaryrefslogtreecommitdiff
path: root/day11/part2.rb
blob: 0be5a5cdc3e51fea1e39ae2a9cb89b02b3e1206c (plain)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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(&:*)