2023-10-07 17:12:47 +01:00
|
|
|
package anagram
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"io"
|
|
|
|
"sort"
|
|
|
|
|
|
|
|
"github.com/ray1729/puzzle-solver/util"
|
|
|
|
)
|
|
|
|
|
|
|
|
type DB interface {
|
|
|
|
FindAnagrams(s string) []string
|
2023-10-08 14:25:57 +01:00
|
|
|
Add(s string)
|
|
|
|
}
|
|
|
|
|
|
|
|
type HashDBImpl map[string][]string
|
|
|
|
|
|
|
|
func New() HashDBImpl {
|
|
|
|
return make(HashDBImpl)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (db HashDBImpl) Add(s string) {
|
|
|
|
k := toKey(s)
|
|
|
|
db[k] = append(db[k], s)
|
2023-10-07 17:12:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func toKey(s string) string {
|
|
|
|
xs := util.LowerCaseAlpha(s)
|
|
|
|
sort.Slice(xs, func(i, j int) bool { return xs[i] < xs[j] })
|
|
|
|
return string(xs)
|
|
|
|
}
|
|
|
|
|
|
|
|
func Load(r io.Reader) (DB, error) {
|
2023-10-08 14:25:57 +01:00
|
|
|
db := New()
|
2023-10-07 17:12:47 +01:00
|
|
|
sc := bufio.NewScanner(r)
|
|
|
|
for sc.Scan() {
|
2023-10-08 14:25:57 +01:00
|
|
|
db.Add(sc.Text())
|
2023-10-07 17:12:47 +01:00
|
|
|
|
|
|
|
}
|
|
|
|
if err := sc.Err(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return db, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d HashDBImpl) FindAnagrams(s string) []string {
|
|
|
|
return d[toKey(s)]
|
|
|
|
}
|