Skip to content

Instantly share code, notes, and snippets.

@seliverstov-maxim
Last active September 29, 2015 05:44
Show Gist options
  • Select an option

  • Save seliverstov-maxim/1f8765682d4d318dba26 to your computer and use it in GitHub Desktop.

Select an option

Save seliverstov-maxim/1f8765682d4d318dba26 to your computer and use it in GitHub Desktop.
Calc
module Converter
PRIORITIES = {')' => 0, '(' => 0, '+' => 1, '-' => 1, '*' => 2, '/' => 3 }
module_function
def polish(inp_exp)
res = []
stack = []
exp = inp_exp.scan(/\d+|\(|\)|\+|\-|\*|\//)
exp.each do |e|
res.push(e.to_i) && next if e.to_s =~ /\d+/
stack.push(e) && next if e.to_s =~ /\(/
while(!stack.empty? && (PRIORITIES[stack.last] > PRIORITIES[e]) && (stack.last != '('))
res.push(stack.pop)
end
stack.pop && next if e == ')'
stack.push(e)
end
res.concat(stack.reverse).join(' ')
end
end
module Calc
module_function
def execute(exp)
stack = []
exp.split(' ').each do |e|
stack.push(e.to_i) && next if e.to_s =~ /\d+/
args = stack.pop 2
stack.push(args.reduce(e))
end
stack
end
end
p_str = Converter.polish('((2 + 2 * 2) * 10) / (2 + 3)')
p Calc.execute(p_str)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment