Skip to content

Commit 8c56f5b

Browse files
committed
Add day 10: Balance Bots
1 parent f2414a1 commit 8c56f5b

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

10_balance_bots.rb

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
Bot = Struct.new(:id, :nums, :low_to, :high_to) {
2+
def <<(n)
3+
nums << n
4+
nums.sort!
5+
puts id if nums == [17, 61]
6+
end
7+
8+
def ready?
9+
nums.size == 2
10+
end
11+
12+
def run!
13+
[low_to, high_to].zip(nums.shift(2)).select { |to, num|
14+
to << num
15+
to.is_a?(Bot) && to.ready?
16+
}.map(&:first)
17+
end
18+
}
19+
20+
bots = Hash.new { |h, k| h[k] = Bot.new(k, []) }
21+
outputs = Hash.new { |h, k| h[k] = [] }
22+
23+
ARGF.each_line { |l|
24+
words = l.split
25+
26+
parse_target = ->(at:) {
27+
case (type = words[at])
28+
when 'bot'; bots
29+
when 'output'; outputs
30+
else raise "what is a #{type}?"
31+
end[Integer(words[at + 1])]
32+
}
33+
34+
case (cmd = words[0])
35+
when 'value'; bots[Integer(words[-1])] << Integer(words[1])
36+
when 'bot'
37+
bot = bots[Integer(words[1])]
38+
bot.low_to = parse_target[at: 5]
39+
bot.high_to = parse_target[at: -2]
40+
else raise "what is a #{cmd}?"
41+
end
42+
}
43+
44+
ready_bots = bots.values.select(&:ready?)
45+
ready_bots = ready_bots.flat_map(&:run!) until ready_bots.empty?
46+
47+
puts (0..2).map { |i| outputs[i].first }.reduce(:*)

0 commit comments

Comments
 (0)