algorithms/fundamentals/exrecises/math_evaluator/evaluator.go

48 lines
1 KiB
Go
Raw Permalink Normal View History

2021-11-08 22:58:25 +02:00
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 {
2021-12-15 23:45:29 +02:00
operations := stack.NewStack[string]()
values := stack.NewStack[int]()
2021-11-08 22:58:25 +02:00
for _, part := range strings.Split(exression, " ") {
isOperation := part == "+" || part == "-" || part == "*" || part == "/" || part == "sqrt"
if part == "(" {
continue
} else if part == ")" {
lastOperation := operations.Pop()
2021-12-15 23:45:29 +02:00
lastValue := values.Pop()
2021-11-08 22:58:25 +02:00
switch lastOperation {
case "+":
2021-12-15 23:45:29 +02:00
lastValue = values.Pop() + lastValue
2021-11-08 22:58:25 +02:00
case "-":
2021-12-15 23:45:29 +02:00
lastValue = values.Pop() - lastValue
2021-11-08 22:58:25 +02:00
case "*":
2021-12-15 23:45:29 +02:00
lastValue = values.Pop() * lastValue
2021-11-08 22:58:25 +02:00
case "/":
2021-12-15 23:45:29 +02:00
lastValue = values.Pop() / lastValue
2021-11-08 22:58:25 +02:00
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)
}
}
2021-12-15 23:45:29 +02:00
return values.Pop()
2021-11-08 22:58:25 +02:00
}