Last active
January 3, 2016 13:59
-
-
Save jimfoltz/ae7f2411b822f495a2c3 to your computer and use it in GitHub Desktop.
infix to postfix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "awesome_print" | |
exp = "1 + 2 * 3" | |
exp = "9 + 24 / (7 - 3)" | |
exp = "3 * atan(2/3)" | |
exp = "(12.3mm - 1')*52 - 473 mm/(4 + 2^3)" | |
def prec(op) | |
case op | |
when "+", "-" | |
return 10 | |
when "*", "/" | |
return 20 | |
when "^" | |
return 30 | |
when "(", ")" | |
return 40 | |
else | |
return nil | |
end | |
end | |
def is_operator(t) | |
operators = ["-", "+", "*", "/", "^"] | |
operators.include?(t) | |
end | |
# Anything that is not an operator, parenthesis, or space is a operand | |
def tokenize(exp) | |
operand = "" | |
tokens = [] | |
exp.each_char do |c| | |
if is_operator(c) || c == "(" || c == ")" | |
if operand != "" | |
tokens << operand | |
operand = "" | |
end | |
tokens << c | |
else | |
operand << c unless c == " " | |
end | |
end | |
tokens << operand unless operand.empty? | |
return tokens | |
end | |
def infix2postfix(tokens) | |
output = [] | |
stack = [] | |
tokens.each do |token| | |
if is_operator(token) | |
while (!stack.empty? && is_operator(stack[-1]) && prec(stack[-1]) >= prec(token)) | |
output << stack.pop | |
end | |
stack << token | |
next | |
end | |
if token == "(" | |
stack.push token | |
next | |
end | |
if token == ")" | |
while stack[-1] && stack[-1] != "(" | |
output << stack.pop | |
end | |
stack.pop | |
next | |
end | |
output << token | |
end # do loop | |
while (!stack.empty?) | |
output << stack.pop | |
end | |
return output | |
end | |
def eval_postfix(arr) | |
stack = [] | |
arr.each do |elm| | |
end | |
end | |
puts exp | |
tokens = tokenize exp | |
puts "Tokens:" | |
ap tokens | |
postfix = infix2postfix(tokens) | |
puts | |
puts "Postfix:" | |
ap postfix |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment