aboutsummaryrefslogtreecommitdiff
path: root/day11/part1.rb
blob: f4890bcfdb2c4bea1adb8e1c5403858325de46a8 (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
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
    @inspections += @items.count
    ret = []
    until @items.empty?
      old = @items.shift
      new = eval(@op) / 3
      ret << [(new % @test == 0 ? @iftrue : @iffalse), new]
    end
    ret
  end
end

class Game
  def initialize
    @monkeys = []
  end

  def <<(monkey)
    @monkeys << monkey
  end

  def round
    @monkeys.each do |monkey|
      monkey.turn.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
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
  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

20.times do
  game.round
end
puts game.inspections.max(2).inject(&:*)