42 lines
847 B
Go
42 lines
847 B
Go
|
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
|
||
|
}
|