Created
September 6, 2017 04:22
-
-
Save courtneyfaulkner/c41defa8166bedd3f50a96292f5fc279 to your computer and use it in GitHub Desktop.
[RPNCalculator] #practice
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
import java.util.*; | |
class RpnCalculator { | |
static void main(String[] args) { | |
Calculator calc = new Calculator() | |
'4 6 3 + 9 3 - * 1 1 ^ - +'.split(' ').each {calc.enter(it)} | |
} | |
} | |
class Calculator { | |
Stack stack = [] as Stack | |
def calculate = {action-> return { action.call(stack.pop(), stack.pop()) }} | |
def actions = [ | |
'+': calculate {a,b -> b + a}, | |
'-': calculate {a,b -> b - a}, | |
'*': calculate {a,b -> b * a}, | |
'/': calculate {a,b -> b / a}, | |
'^': calculate {a,b -> b ** a} | |
] | |
void enter(String entry) { | |
def action = actions[entry] | |
BigDecimal last = null | |
if (action) { | |
if (stack.size() > 1) { | |
last = action.call() | |
stack.push(last) | |
} else if (stack.size() == 1) { | |
last = stack.peek() | |
} | |
} else if (entry.isBigDecimal()) { | |
stack.push(entry as BigDecimal) | |
last = entry as BigDecimal | |
} | |
if (last != null) { | |
println "$stack: $last" | |
} else { | |
println stack | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment