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.56 tracks/go/exercises/wordy/example.go
trackler-2.2.1.55 tracks/go/exercises/wordy/example.go
trackler-2.2.1.54 tracks/go/exercises/wordy/example.go
trackler-2.2.1.53 tracks/go/exercises/wordy/example.go
trackler-2.2.1.52 tracks/go/exercises/wordy/example.go
trackler-2.2.1.51 tracks/go/exercises/wordy/example.go
trackler-2.2.1.50 tracks/go/exercises/wordy/example.go
trackler-2.2.1.49 tracks/go/exercises/wordy/example.go
trackler-2.2.1.48 tracks/go/exercises/wordy/example.go
trackler-2.2.1.47 tracks/go/exercises/wordy/example.go
trackler-2.2.1.46 tracks/go/exercises/wordy/example.go
trackler-2.2.1.45 tracks/go/exercises/wordy/example.go
trackler-2.2.1.44 tracks/go/exercises/wordy/example.go
trackler-2.2.1.43 tracks/go/exercises/wordy/example.go
trackler-2.2.1.42 tracks/go/exercises/wordy/example.go
trackler-2.2.1.41 tracks/go/exercises/wordy/example.go
trackler-2.2.1.40 tracks/go/exercises/wordy/example.go
trackler-2.2.1.39 tracks/go/exercises/wordy/example.go
trackler-2.2.1.38 tracks/go/exercises/wordy/example.go
trackler-2.2.1.37 tracks/go/exercises/wordy/example.go