exercism/go/kindergarten-garden/kindergarten.go
2016-09-12 17:41:46 -05:00

94 lines
1.8 KiB
Go

package kindergarten
import (
"errors"
"sort"
"strings"
)
type Garden struct {
children []string
rows []string
}
func NewGarden(diagram string, children []string) (*Garden, error) {
var err error
g := new(Garden)
g.rows = strings.Split(diagram[1:], "\n")
g.children = children
if diagram[0] != '\n' {
err = errors.New("Wrong diagram format")
} else if len(g.rows) == 0 {
err = errors.New("No rows")
} else if len(g.children) == 0 {
err = errors.New("No children")
} else if len(g.rows[0]) != len(g.rows[1]) {
err = errors.New("Mismatched rows")
} else {
for i := range g.rows {
if len(g.rows[i])%2 != 0 {
err = errors.New("Odd number of cups")
break
}
for j := range g.rows[i] {
tst := g.rows[i][j]
switch tst {
case 'R':
case 'C':
case 'G':
case 'V':
default:
err = errors.New("Invalid Cup Codes")
}
}
if err != nil {
break
}
}
for i := range g.children {
if i > 0 {
if g.children[i] == g.children[i-1] {
err = errors.New("Duplicate Children")
break
}
}
}
}
return g, err
}
func (g *Garden) Plants(child string) ([]string, bool) {
var i int
var ret []string
var found bool
c := g.children
sort.Strings(c)
for i = 0; i < len(c); i++ {
if c[i] == child {
found = true
break
}
}
if !found || len(g.rows) == 0 || len(g.rows[0]) <= 2*i {
return ret, found
}
for j := range []int{0, 1} {
for k := range []int{0, 1} {
switch g.rows[j][(i*2 + k)] {
case 'G':
ret = append(ret, "grass")
case 'C':
ret = append(ret, "clover")
case 'R':
ret = append(ret, "radishes")
case 'V':
ret = append(ret, "violets")
}
}
}
return ret, found
}
// kindergarten_garden_test.go:140: Garden 6 lookup Patricia =
// [radishes radishes grass clover], want [violets clover radishes violets].