Skip to content

Instantly share code, notes, and snippets.

@lkrych
Created August 5, 2018 18:22
Show Gist options
  • Save lkrych/3a65f09ca3a8eb4dc0053afdcd15e135 to your computer and use it in GitHub Desktop.
Save lkrych/3a65f09ca3a8eb4dc0053afdcd15e135 to your computer and use it in GitHub Desktop.
func reversePolish(arithmeticExpression string) int {
//create regexp for matching against operators
r := regexp.MustCompile("[+-/*]")
//split input by spaces
splitInput := strings.Split(arithmeticExpression, " ")
//init Stack
s := &Stack{}
for _, char := range splitInput {
if r.Match([]byte(char)) {
int1 := s.pop()
int2 := s.pop()
expression := fmt.Sprintf("%v %v %v", int1, char, int2)
//use the govaluate package to evalute the arithmetic expression
eval, err := govaluate.NewEvaluableExpression(expression)
if err != nil {
fmt.Printf("There was an error building your expression: %v \n", expression)
log.Fatal("The program is shutting down")
}
result, err := eval.Evaluate(nil)
if err != nil {
fmt.Printf("There was an error evaluating your expression: %v \n", expression)
log.Fatal("The program is shutting down")
}
fmt.Printf("The expression being evaluated is %v = %v \n", expression, result)
//govaluates returns an interface so we need to convert from interface to int
intResult := int(result.(float64))
s.push(intResult)
} else {
//if there isn't an operator, push the number onto the stack
intVal, err := strconv.Atoi(char)
if err != nil {
fmt.Printf("%v is not a valid integer \n", char)
log.Fatal("Please use valid characters for this program: 0-9 and *-/+")
}
s.push(intVal)
}
}
//return the end result
total := s.pop()
fmt.Printf("The evaluation of %v yields %v \n", opts.UserInput, total)
return total
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment