Last active
July 9, 2020 18:39
-
-
Save maniish-jaiin/ca99d6d5977cdc2e0771d8e4a72a8188 to your computer and use it in GitHub Desktop.
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
import java.util.* | |
fun main() { | |
println(evaluate("4 2 /")) | |
} | |
fun evaluate(expr: String): Float { | |
val chars = expr.split(" ") | |
val stack = Stack<Float>() | |
val operator = operationForOperator() | |
for (c in chars) { | |
operator[c]?.let { stack.push(operate(it, stack)) } ?: stack.push(c.toFloat()) | |
} | |
return stack.pop() | |
} | |
fun operationForOperator(): Map<String, (Float, Float) -> Float> { | |
return mapOf( | |
"+" to { a, b -> a + b }, | |
"-" to { a, b -> a - b }, | |
"*" to { a, b -> a * b }, | |
"/" to { a, b -> a / b } | |
) | |
} | |
fun operate(function: (a: Float, b: Float) -> Float, stack: Stack<Float>): Float { | |
val numberOne = stack.pop() | |
val numberTwo = stack.pop() | |
return function(numberTwo, numberOne) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment