Skip to content

Instantly share code, notes, and snippets.

@maniish-jaiin
Last active July 9, 2020 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maniish-jaiin/ca99d6d5977cdc2e0771d8e4a72a8188 to your computer and use it in GitHub Desktop.
Save maniish-jaiin/ca99d6d5977cdc2e0771d8e4a72a8188 to your computer and use it in GitHub Desktop.
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