-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpuzzle.go
56 lines (52 loc) · 1.44 KB
/
puzzle.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main
import (
"fmt"
)
type Puzzle struct {
requiredLetter rune
allowedLetters map[rune]bool
}
func NewPuzzle(requiredLetter rune, otherLetters string) (Puzzle, error) {
if len(otherLetters) != 6 {
return Puzzle{}, fmt.Errorf("must have 6 otherLetters, found %d", len(otherLetters))
}
allowedLetters := make(map[rune]bool)
for _, ch := range otherLetters {
_, exists := allowedLetters[ch]
if exists {
return Puzzle{}, fmt.Errorf("otherLetters cannot have any duplicates, found: '%s'", string(ch))
}
allowedLetters[ch] = true
}
if _, exists := allowedLetters[requiredLetter]; exists {
return Puzzle{}, fmt.Errorf("otherLetters cannot contain the requiredLetter: '%s'", string(requiredLetter))
}
allowedLetters[requiredLetter] = true
return Puzzle{requiredLetter, allowedLetters}, nil
}
func (puzzle Puzzle) ResultFor(candidate string) Result {
foundRequired := false
allAreAllowed := true
for _, candidateCh := range candidate {
if candidateCh == puzzle.requiredLetter {
foundRequired = true
}
if _, exists := puzzle.allowedLetters[candidateCh]; !exists {
allAreAllowed = false
break
}
}
if foundRequired && allAreAllowed {
uniqueLetters := make(map[rune]bool)
for _, candidateCh := range candidate {
uniqueLetters[candidateCh] = true
}
if len(uniqueLetters) == 7 {
return NewPangramResult(candidate)
} else {
return NewValidResult(candidate)
}
} else {
return NewInvalidResult(candidate)
}
}