Problem
Given an arithmetic string like 2+2*3 calculate result 8.
Assumptions you can make
- string will be always well formed (no error checking needs to be done)
- only operators passed in string will be + and *
- only single digit numbers allowed
Example
input = 2*2*2+2*1*5
output = 18
input = 2+2*3
output = 8
Hers is scala code for the same
object Expression extends App {
implicit class Converter(char: Char) {
def toNum: Int = char - '0'
}
def evaluateExpression(s :List[Char]): Int = {
s match {
case left::op::List(right) => // a+b or a*b
op match {
case '+' => left.toNum + right.toNum
case _ => left.toNum * right.toNum
}
case left::op::right => // a+b*c or a*b+c
op match {
case '+' =>
left.toNum + evaluateExpression(right)
case '*' =>
val nextAdd = right indexOf '+'
val (multiplication ,pendingExpression) = if (nextAdd == -1) {
(right,List[Char]())
} else {
(right.take(nextAdd), right.drop(nextAdd + 1))
}
val product = (multiplication.filter( _ != '*') map (_.toNum)).foldLeft(left.toNum) (_ * _)
if (pendingExpression.isEmpty) product
else product + evaluateExpression(pendingExpression)
}
}
}
List("3*3*3", "2+2*3", "0*0*1", "0+0*1", "0*0*1", "2+2*3*3", "2+2+2*3+2+2") foreach { expr =>
println(expr + " = " + evaluateExpression(expr.toList))
}
}
Output for above code
3*3*3 = 27
2+2*3 = 8
0*0*1 = 0
0+0*1 = 0
0*0*1 = 0
2+2*3*3 = 20
2+2+2*3+2+2 = 14