diff --git a/fundamentals/math_evaluator/evaluator.go b/fundamentals/math_evaluator/evaluator.go new file mode 100644 index 0000000..0a46810 --- /dev/null +++ b/fundamentals/math_evaluator/evaluator.go @@ -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) +} diff --git a/fundamentals/math_evaluator/evaluator_test.go b/fundamentals/math_evaluator/evaluator_test.go new file mode 100644 index 0000000..5c18965 --- /dev/null +++ b/fundamentals/math_evaluator/evaluator_test.go @@ -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) + } +}