-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathevaluate_infix.rb
74 lines (57 loc) · 1.39 KB
/
evaluate_infix.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
# Problem:
# Given an arithmetic expression with * / - + operators and single digit numbers
# evaluate it and return the result
#
# Given: 1 + 2 / 1 + 3 * 2
# Result: 9, since 1 + 2 + 6
require_relative "stack"
class EvaluateInfix
attr_accessor :operands, :operators, :expression
def initialize(arr)
@operands = Stack.new
@operators = Stack.new
@expression = arr
end
def run
return 0 if expression.empty?
expression.each do |char|
if operand? char
operands.push char
elsif operator? char
process(operators, operands) while !operators.empty? && precedence(operators.peek) >= precedence(char)
operators.push char
end
end
process(operators, operands) until operators.empty?
operands.pop.to_i
end
private
def operator?(char)
["+", "-", "/", "*"].include?(char)
end
def operand?(char)
return false if operator?(char)
char >= "0" || char <= "9"
end
def precedence(char)
return 2 if ["/", "*"].include?(char)
return 1 if ["+", "-"].include?(char)
end
def process(operator_stack, operand_stack)
j = operand_stack.pop.to_i
i = operand_stack.pop.to_i
op = operator_stack.pop
result = 0
case op
when "/"
result = i / j
when "*"
result = i * j
when "+"
result = i + j
when "-"
result = i - j
end
operands.push(result.to_s)
end
end