-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday10_part1.rb
107 lines (85 loc) · 2.32 KB
/
day10_part1.rb
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
class Robot
attr_accessor :low,:high, :number, :values,:input_receive
def initialize(number)
@number = number
@values = []
@low = nil
@high = nil
end
def can_proceed
@values.length >= 2
end
def proceed
sorted = @values.sort
puts "#{number}: #{@low.number if low } receives #{sorted[0]}, #{@high.number if number} receives #{sorted[1]}"
@low.receive(sorted[0]) if @low
@high.receive(sorted[1]) if @high
@values = []
sorted
end
def receive(value)
puts "#{number} received #{value}"
@values << value
end
def to_s
"bot #{number}: #{@values.inspect} => low: #{@low.number if @low}, high: #{@high.number if @high}"
end
def inspect
to_s
end
end
class Processor
def initialize(commands)
@bots = []
commands.each do |c|
if (c.match(/value (\d+) goes to bot (\d+)/))
puts c
bot($2.to_i).receive($1.to_i)
elsif (c.match(/bot (\d+) gives low to (output|bot) (\d+) and high to (output|bot) (\d+)/))
low_receiver = ($2 == "bot") ? bot($3.to_i): nil
raise c if bot($1.to_i).low != nil
bot($1.to_i).low = low_receiver
high_receiver = ($4 == "bot") ? bot($5.to_i) : nil
raise c if bot($1.to_i).high != nil
bot($1.to_i).high = high_receiver
puts "#{c} => #{bot($1.to_i).number} => low: #{low_receiver.number if low_receiver}, high:#{high_receiver.number if high_receiver}"
else
raise c
end
end
#puts @bots.inspect
end
def process
found = false
round = 0
while (!found)
puts round += 1
@bots.each do |bot|
if (bot.can_proceed)
result = bot.proceed
if ((result & [17,61]).length == 2)
puts "Found answer: #{bot.number}"
found = true
raise "Found"
else
puts result.inspect
end
end
end
end
end
def bot(number)
if (!@bots[number])
@bots[number ] = Robot.new(number)
end
@bots[number]
end
end
test = "value 5 goes to bot 2
bot 2 gives low to bot 1 and high to bot 0
value 3 goes to bot 1
bot 1 gives low to output 1 and high to bot 0
bot 0 gives low to output 2 and high to output 0
value 2 goes to bot 2"
#Processor.new(test.split("\n"))
Processor.new(File.new("day10_input.txt").readlines).process