74 lines
1.3 KiB
Go
74 lines
1.3 KiB
Go
package words
|
|
|
|
import (
|
|
"encoding/csv"
|
|
"fmt"
|
|
"io"
|
|
"math/rand"
|
|
"matrix-bot/krkrkr"
|
|
"os"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type Dictionary struct {
|
|
words map[int][]string // key: word length, value: slice of words of that length
|
|
rng *rand.Rand
|
|
}
|
|
|
|
func New(path string) (*Dictionary, error) {
|
|
file, err := os.Open(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer file.Close()
|
|
|
|
reader := csv.NewReader(file)
|
|
|
|
words := make(map[int][]string)
|
|
for {
|
|
record, err := reader.Read()
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(record) > 0 {
|
|
word := strings.ToUpper(strings.TrimSpace(record[0]))
|
|
l := len(word)
|
|
if l > 0 {
|
|
words[l] = append(words[l], word)
|
|
}
|
|
}
|
|
}
|
|
|
|
return &Dictionary{
|
|
words: words,
|
|
rng: rand.New(rand.NewSource(time.Now().UnixNano())),
|
|
}, nil
|
|
}
|
|
|
|
func (d *Dictionary) RandomWord(length int) (string, error) {
|
|
words := d.words[length]
|
|
if len(words) == 0 {
|
|
return "", fmt.Errorf("no words of length %d", length)
|
|
}
|
|
return words[d.rng.Intn(len(words))], nil
|
|
}
|
|
|
|
func (d *Dictionary) DailyWord(length int) string {
|
|
words := d.words[length]
|
|
if len(words) == 0 {
|
|
return ""
|
|
}
|
|
return words[krkrkr.Today()%len(words)]
|
|
}
|
|
|
|
func (d *Dictionary) Contains(word string) bool {
|
|
word = strings.ToUpper(strings.TrimSpace(word))
|
|
l := len(word)
|
|
return slices.Contains(d.words[l], word)
|
|
}
|