summaryrefslogtreecommitdiff
path: root/go/anagram/anagram.go
blob: e7bf2f925760d4a3bde39090a2b3f1c171a61777 (plain)
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
package anagram

import (
	"sort"
	"strings"
)

type byByte []byte

func (b byByte) Len() int           { return len(b) }
func (b byByte) Less(i, j int) bool { return b[i] < b[j] }
func (b byByte) Swap(i, j int)      { b[i], b[j] = b[j], b[i] }

func Detect(s string, cand []string) []string {
	var ret []string
	s = strings.ToLower(s)
	b := byByte(s)
	sort.Sort(b)
	for _, v := range cand {
		v = strings.ToLower(v)
		if len(v) == len(s) && v != s {
			c := byByte(v)
			sort.Sort(c)
			if string(c) == string(b) {
				ret = append(ret, v)
			}
		}
	}
	return ret
}