algorithms/fundamentals/exrecises/math_evaluator/evaluator.go
2021-11-16 20:36:42 +02:00

47 lines
1.1 KiB
Go

package mathevaluator
import (
"math"
"strconv"
"strings"
"github.com/fotonmoton/algorithms/fundamentals/stack"
)
// Dijkstra's two stack algorithm for equation evaluation
func Evaluate(exression string) int {
operations := stack.NewStack()
values := stack.NewStack()
for _, part := range strings.Split(exression, " ") {
isOperation := part == "+" || part == "-" || part == "*" || part == "/" || part == "sqrt"
if part == "(" {
continue
} else if part == ")" {
lastOperation := operations.Pop()
lastValue := values.Pop().(int)
switch lastOperation {
case "+":
lastValue = values.Pop().(int) + lastValue
case "-":
lastValue = values.Pop().(int) - lastValue
case "*":
lastValue = values.Pop().(int) * lastValue
case "/":
lastValue = values.Pop().(int) / lastValue
case "sqrt":
lastValue = int(math.Sqrt(float64(lastValue)))
}
values.Push(lastValue)
} else if isOperation {
operations.Push(part)
} else {
newValue, _ := strconv.Atoi(part)
values.Push(newValue)
}
}
return values.Pop().(int)
}