-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path21-1.rb
executable file
·47 lines (34 loc) · 919 Bytes
/
21-1.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
#!/usr/bin/env ruby
$monkeys = {}
class Monkey
def initialize(name, operation)
number_format = /^(?<num>[[:digit:]]+)$/
calc_format = /^(?<m1>[[:alpha:]]+) (?<op>[-+*\/]) (?<m2>[[:alpha:]]+)$/
@operation = operation
@name = name
@value = nil
if m = number_format.match(@operation)
@value = m['num'].to_i
else
m = calc_format.match(@operation)
@m1 = m['m1']
@op = m['op']
@m2 = m['m2']
end
end
def value
return @value if @value
@value = $monkeys[@m1].value.send(@op, $monkeys[@m2].value)
end
def to_s
"<#{self.class}: #{@name} = #{@operation} (#{@value})>"
end
alias inspect to_s
end
input = File.read('21.input').lines
monkey_format = /^(?<name>[[:alpha:]]+): (?<op>.*)$/
input.each do |line|
m = monkey_format.match line
$monkeys[m['name']] = Monkey.new(m['name'], m['op'])
end
print $monkeys['root'].value, "\n"