evaluator
This commit is contained in:
parent
a35bb36872
commit
d436ced2d6
2 changed files with 77 additions and 0 deletions
47
fundamentals/math_evaluator/evaluator.go
Normal file
47
fundamentals/math_evaluator/evaluator.go
Normal 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)
|
||||
}
|
30
fundamentals/math_evaluator/evaluator_test.go
Normal file
30
fundamentals/math_evaluator/evaluator_test.go
Normal 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)
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue