-
Notifications
You must be signed in to change notification settings - Fork 0
/
day8_eval.rb
58 lines (44 loc) · 864 Bytes
/
day8_eval.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
module Day8
REGEXP = %r{
([[:alpha:]]+)
\s
(inc|dec)
\s
(-?\d+)
\s
if
\s
([[:alpha:]]+)
\s
(
[<>=!]+
\s
-?\d+
)
}x
module_function
def each
File.readlines('./day8.txt').each do |line|
if m = line.match(REGEXP)
yield m[1..5]
end
end
end
def solve
registers = {}
exe_code = ''
instructions = []
max = 0
each do |object_name, op, mod, object_cond, cond|
registers[object_name.to_sym] = 0
registers[object_cond.to_sym] = 0
op = op == 'dec' ? '-= ' : '+= '
obj = "registers[:#{object_name}]"
exe_code << "#{obj} #{op} #{mod} if registers[:#{object_cond}] #{cond}\n"
exe_code << "max = #{obj} if #{obj} > max\n"
end
eval(exe_code)
[registers.values.max, max]
end
end
p Day8.solve