package anagram
import (
"strings"
)
// Detect returns a list of anagrams for input from candidates.
func Detect(input string, candidates []string) []string {
var ret []string
input = strings.ToLower(input)
for _, word := range candidates {
if checkCandidate(input, strings.ToLower(word)) {
ret = append(ret, word)
}
}
return ret
}
func checkCandidate(letters string, candidate string) bool {
// check for self anagram
if letters == candidate {
return false
}
for _, ch := range candidate {
if strings.ContainsRune(letters, ch) {
// remove the mathing rune from letters
letters = strings.Replace(letters, string(ch), "", 1)
continue
}
return false
}
// we have found all the letters and there are no runes left
if letters == "" {
return true
}
return false
}