Last active
December 14, 2021 11:57
-
-
Save lwiecek/952b6bca77c843e83c5d5577da9fd37e to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calculator in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strconv" | |
"strings" | |
) | |
func pop2(stack []float64) ([]float64, float64, float64) { | |
var ab []float64 | |
stack, ab = stack[:len(stack)-2], stack[len(stack)-2:] | |
return stack, ab[0], ab[1] | |
} | |
func ReversePolishNotation(s string) (float64, error) { | |
var stack []float64 | |
var tokens = strings.Fields(s) | |
var value float64 | |
for _, token := range tokens { | |
switch token { | |
case "+", "-", "*", "/": | |
var a, b float64 | |
if len(stack) < 2 { | |
return 0, fmt.Errorf("not enough elmenents on the stack to calculate %s", token) | |
} | |
stack, a, b = pop2(stack) | |
switch token { | |
case "+": | |
value = a + b | |
case "-": | |
value = a - b | |
case "*": | |
value = a * b | |
case "/": | |
value = a / b | |
} | |
default: | |
var err error | |
value, err = strconv.ParseFloat(token, 64) | |
if err != nil { | |
return 0, fmt.Errorf("invalid token %s", token) | |
} | |
} | |
stack = append(stack, value) | |
} | |
if len(stack) != 1 { | |
return 0, fmt.Errorf("incomplete expression %s", stack) | |
} | |
return stack[0], nil | |
} | |
func main() { | |
fmt.Println(ReversePolishNotation("0")) | |
fmt.Println(ReversePolishNotation("1 2 +")) | |
fmt.Println(ReversePolishNotation("2 2 + 2 *")) | |
fmt.Println(ReversePolishNotation("1 100 /")) | |
fmt.Println(ReversePolishNotation(" 100 1 / ")) | |
fmt.Println(ReversePolishNotation("")) | |
fmt.Println(ReversePolishNotation("1 2 3")) | |
fmt.Println(ReversePolishNotation("+ -")) | |
fmt.Println(ReversePolishNotation("abc")) | |
fmt.Println(ReversePolishNotation("-1")) | |
fmt.Println(ReversePolishNotation("-1 -0.0 +")) | |
fmt.Println(ReversePolishNotation("-2.5 -1e10 *")) | |
fmt.Println(ReversePolishNotation("0 0 /")) | |
fmt.Println(ReversePolishNotation("1 0 /")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment