evaluator

This commit is contained in:
Gregory 2021-11-08 22:58:25 +02:00
parent a35bb36872
commit d436ced2d6
2 changed files with 77 additions and 0 deletions

View file

@ -0,0 +1,47 @@
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)
}

View file

@ -0,0 +1,30 @@
package mathevaluator
import (
"log"
"testing"
)
func TestSimple(t *testing.T) {
result := Evaluate("( 1 + 1 )")
if result != 2 {
log.Fatalf("wrong answer: %v", result)
}
}
func TestSqrt(t *testing.T) {
result := Evaluate("sqrt ( 9 )")
if result != 3 {
log.Fatalf("wrong answer: %v", result)
}
}
func TestComplex(t *testing.T) {
result := Evaluate("( ( 1 + ( 2 - ( 3 * ( 4 / ( 1 + 1 ) ) ) ) ) + sqrt ( 9 ) )")
if result != 0 {
log.Fatalf("wrong answer: %v", result)
}
}