Sha256: 78546f4c7fae9a0bd15e713e40ebc83ac4782465e6ee4a98a56aa3d77d414f04

Contents?: true

Size: 1.12 KB

Versions: 190

Compression:

Stored size: 1.12 KB

Contents

package wordy

import (
	"strconv"
	"strings"
)

const testVersion = 1

func Answer(q string) (a int, ok bool) {
	w := strings.Fields(q)
	if len(w) < 3 { // length check for first two words and last word
		return
	}
	if w[0] != "What" || w[1] != "is" { // first two words required
		return
	}
	w = w[2:]
	last := len(w) - 1
	wl := w[last]
	if wl[len(wl)-1] != '?' { // trailing ? required
		return
	}
	w[last] = wl[:len(wl)-1]
	a, err := strconv.Atoi(w[0]) // first word after preamble must be a number
	if err != nil {
		return
	}
	for i := 1; i < len(w); i++ { // remainder of q must alternate between op, number
		op := w[i]
		i++
		switch op {
		case "multiplied", "divided":
			if i == len(w) || w[i] != "by" { // length check, required word
				return
			}
			i++ // consume
		}
		if i == len(w) { // length check for operand
			return
		}
		x, err := strconv.Atoi(w[i]) // must be a number
		if err != nil {
			return
		}
		switch op { // apply operator
		case "plus":
			a += x
		case "minus":
			a -= x
		case "multiplied":
			a *= x
		case "divided":
			a /= x
		default: // valid operator not found
			return
		}
	}
	return a, true
}

Version data entries

190 entries across 190 versions & 1 rubygems

Version Path
trackler-2.2.1.36 tracks/go/exercises/wordy/example.go
trackler-2.2.1.35 tracks/go/exercises/wordy/example.go
trackler-2.2.1.34 tracks/go/exercises/wordy/example.go
trackler-2.2.1.33 tracks/go/exercises/wordy/example.go
trackler-2.2.1.32 tracks/go/exercises/wordy/example.go
trackler-2.2.1.31 tracks/go/exercises/wordy/example.go
trackler-2.2.1.30 tracks/go/exercises/wordy/example.go
trackler-2.2.1.29 tracks/go/exercises/wordy/example.go
trackler-2.2.1.28 tracks/go/exercises/wordy/example.go
trackler-2.2.1.27 tracks/go/exercises/wordy/example.go
trackler-2.2.1.26 tracks/go/exercises/wordy/example.go
trackler-2.2.1.25 tracks/go/exercises/wordy/example.go
trackler-2.2.1.24 tracks/go/exercises/wordy/example.go
trackler-2.2.1.23 tracks/go/exercises/wordy/example.go
trackler-2.2.1.22 tracks/go/exercises/wordy/example.go
trackler-2.2.1.21 tracks/go/exercises/wordy/example.go
trackler-2.2.1.20 tracks/go/exercises/wordy/example.go
trackler-2.2.1.19 tracks/go/exercises/wordy/example.go
trackler-2.2.1.18 tracks/go/exercises/wordy/example.go
trackler-2.2.1.17 tracks/go/exercises/wordy/example.go