Created
November 11, 2017 21:08
-
-
Save fynntimes/a15dc6781588408cd0aa1f8f90c681f6 to your computer and use it in GitHub Desktop.
A rudimentary mathematical expression evaluator in Kotlin.
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.* | |
import javax.script.ScriptEngine | |
import javax.script.ScriptEngineManager | |
import javax.script.ScriptException | |
// Instance variables | |
val engine: ScriptEngine = ScriptEngineManager().getEngineByName("JavaScript") | |
val jsMathMap = hashMapOf("sin" to "Math.sin", "cos" to "Math.cos", "tan" to "Math.tan", "pi" to "Math.PI") | |
fun main(args: Array<String>) { | |
val scanner = Scanner(System.`in`) | |
val expr = scanner.nextLine() | |
val modifiedExpr = mathToJs(expr) | |
println("$modifiedExpr = ${eval(modifiedExpr)}") | |
} | |
/** | |
* Evaluates a mathematical expression. | |
*/ | |
fun eval(expr: String): Number { | |
return try { | |
engine.eval(expr) as Number | |
} catch (ex: ScriptException) { | |
Double.NaN | |
} | |
} | |
/** | |
* JavaScript contains a lot of math utilities, but requires | |
* a reference to methods in the Math class. This method uses | |
* the "jsMathMap" to convert standard mathematical notation | |
* to valid Javascript. | |
*/ | |
fun mathToJs(expr: String): String { | |
var ret: String = expr | |
jsMathMap.forEach { old, new -> | |
run { | |
ret = ret.replace(old, new) | |
} | |
} | |
return ret | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment