-
Notifications
You must be signed in to change notification settings - Fork 0
/
day18.rb
64 lines (57 loc) · 1.8 KB
/
day18.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
input = File.read("day18_input.txt").split("\n").map { |l| l.scan(/\d+|[+*()]/) }
def parse(expr)
loop do
if subexpr = expr.index('(')
par = parse(expr[subexpr+1..-1])
expr = subexpr > 1 ? expr[0..subexpr-1].concat(par) : par
elsif (eosubexp = expr.index(')')) && eosubexp > 1
return [expr[0..eosubexp-1]].concat(expr[eosubexp+1..-1])
else
break
end
end
return expr
end
# Part 1
def solve(expr)
return expr.to_i if expr.kind_of?(String)
while expr.count > 1
lhs = solve(expr.shift)
op = expr.shift.to_sym
rhs = solve(expr.shift)
expr.unshift([lhs,rhs].reduce(&op).to_s)
end
return expr[0].to_i
end
p input.map { |expr| parse(expr.clone) }.map { |tree| solve(tree) }.sum
# Part 2
def solve2(expr)
return expr.to_i if expr.kind_of?(String)
while expr.count > 1
opidx = expr.index('+') || expr.index('*')
lhs = solve2(expr.slice!(opidx-1))
op = expr.slice!(opidx-1).to_sym
rhs = solve2(expr.slice!(opidx-1))
expr.insert(opidx-1,[lhs,rhs].reduce(&op).to_s)
end
return expr[0].to_i
end
p input.map { |expr| parse(expr) }.map { |tree| solve2(tree) }.sum
# Regex solutions
# Part 1
p File.read("day18_input.txt").split("\n").map { |l|
loop do break unless l.sub!(/\((\d+)\)/, '\1') ||
l.sub!(/(.*?)(\d+\s*[+*]\s*\d+)(.*)/) { "#{$1}#{eval($2)}#{$3}" }
end
l
}.map(&:to_i).sum
# Part 2
p File.read("day18_input.txt").split("\n").map { |l|
loop do
break unless
l.sub!(/\((\d+)\)/, '\1') ||
l.sub!(/(.*?)(\d+\s*[+]\s*\d+)(.*)/) { "#{$1}#{eval($2)}#{$3}" } ||
l.sub!(/^(.*?)(\d+\s*[*]\s*\d+)([^(]*)$/) { "#{$1}#{eval($2)}#{$3}" }
end
l
}.map(&:to_i).sum