Last active
September 29, 2015 05:44
-
-
Save seliverstov-maxim/1f8765682d4d318dba26 to your computer and use it in GitHub Desktop.
Calc
This file contains hidden or 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
| 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