From b8a4ca01b472bb8a9e93be0e1eae92be439e410f Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Sat, 10 Dec 2022 21:34:00 -0800 Subject: [PATCH] [2022][ruby][11.x] --- 2022/ruby/day_11.rb | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 2022/ruby/day_11.rb diff --git a/2022/ruby/day_11.rb b/2022/ruby/day_11.rb new file mode 100644 index 0000000..2bdfcf9 --- /dev/null +++ b/2022/ruby/day_11.rb @@ -0,0 +1,35 @@ +Monkey = Struct.new(:id, :items, :operation, :test, :throw_to) + +monkeys = ARGF.read.split("\n\n").map {|raw| + raw = raw.lines(chomp: true) + id = raw.shift.match(/\d+/)[0].to_i + starting_items = raw.shift.match(/: (.+)/)[1].split(", ").map(&:to_i) + operation_ = raw.shift.match(/: new = (.+)/)[1] + operation = ->(old) { eval(operation_) } + test = raw.shift.match(/\d+/)[0].to_i + t = raw.shift.match(/\d+/)[0].to_i + f = raw.shift.match(/\d+/)[0].to_i + throw_to = ->(n) { (n % test).zero? ? t : f } + Monkey.new(id, starting_items, operation, test, throw_to) +} + +max_worry = monkeys.map(&:test).inject(:*) + +inspections = Hash.new(0) +# 20.times do +10_000.times do + monkeys.each do |monkey| + until monkey.items.empty? + inspections[monkey.id] += 1 + + item = monkey.items.shift + item = monkey.operation.(item) + # item /= 3 + item %= max_worry + to = monkey.throw_to.(item) + monkeys[to].items << item + end + end +end + +p inspections.values.max(2).inject(:*)