-
Notifications
You must be signed in to change notification settings - Fork 5
/
alphabet.go
52 lines (41 loc) · 918 Bytes
/
alphabet.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
package main
import (
"errors"
"flag"
"fmt"
"sort"
)
const _defaultAlphabet alphabet = "abcdefghijklmnopqrstuvwxyz"
type alphabet string
var _ flag.Value = (*alphabet)(nil)
func (al *alphabet) String() string {
return string(*al)
}
func (al *alphabet) Set(alpha string) error {
*al = alphabet(alpha)
return al.Validate()
}
func (al alphabet) Validate() error {
if len(al) < 2 {
return errors.New("alphabet must have at least two items")
}
seen := make(map[rune]struct{}, len(al))
dupes := make(map[rune]struct{})
for _, r := range al {
if _, ok := seen[r]; ok {
dupes[r] = struct{}{}
}
seen[r] = struct{}{}
}
if len(dupes) == 0 {
return nil // success
}
dlist := make([]rune, 0, len(dupes))
for r := range dupes {
dlist = append(dlist, r)
}
sort.Slice(dlist, func(i, j int) bool {
return dlist[i] < dlist[j]
})
return fmt.Errorf("alphabet has duplicates: %q", dlist)
}