exercism/go/wordy/wordy.go

42 lines
847 B
Go
Raw Normal View History

2016-09-03 14:53:54 +00:00
package wordy
import (
"strconv"
"strings"
)
// Answer parses a simple word problem and returns the result
// or false if it wasn't valid
func Answer(inp string) (int, bool) {
var ret int
var operation string
var didOperation bool
words := strings.Fields(inp)
for i := range words {
tstWord := strings.Replace(words[i], "?", "", -1)
if v, err := strconv.Atoi(tstWord); err == nil {
switch operation {
case "":
ret = v
case "plus":
ret += v
didOperation = true
case "minus":
ret -= v
didOperation = true
case "multiplied":
ret *= v
didOperation = true
case "divided":
ret /= v
didOperation = true
}
} else {
if words[i] == "plus" || words[i] == "minus" || words[i] == "multiplied" || words[i] == "divided" {
operation = words[i]
}
}
}
return ret, didOperation
}