-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecond_lab.rb
More file actions
43 lines (37 loc) · 821 Bytes
/
second_lab.rb
File metadata and controls
43 lines (37 loc) · 821 Bytes
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
def infix_to_rpn(expression)
def precedence(operator)
case operator
when '+', '-' then 1
when '*', '/' then 2
else 0
end
end
output = []
stack = []
tokens = expression.scan(/\d+|\+|\-|\*|\/|\(|\)/)
tokens.each do |token|
if token.match(/\d+/)
output << token
elsif token == '('
stack << token
elsif token == ')'
while !stack.empty? && stack.last != '('
output << stack.pop
end
stack.pop
else
while stack.any? && precedence(stack.last) >= precedence(token)
output << stack.pop
end
stack << token
end
end
while !stack.empty?
output << stack.pop
end
return output
end
puts "Enter the mathematical expression: "
expression = gets.chomp
result = infix_to_rpn(expression)
puts result.join(' ')