-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain.go
80 lines (69 loc) · 1.66 KB
/
chain.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"math/rand"
"strings"
)
const (
ChainStart = "\x01S"
ChainEnd = "\x01E"
)
type Chain struct {
chain map[string]map[string]int
}
func NewChain() Chain {
return Chain{make(map[string]map[string]int)}
}
func (c *Chain) Clone(chain *Chain) {
chain.chain = c.chain
}
func (c *Chain) addWord(rootWord, word string) {
if c.chain[rootWord] == nil {
c.chain[rootWord] = make(map[string]int)
}
c.chain[rootWord][word]++
}
func (c *Chain) AddSentence(words []string) {
c.addWord(ChainStart, words[0])
for i := 0; i < len(words)-1; i++ {
c.addWord(words[i], words[i+1])
}
c.addWord(words[len(words)-1], ChainEnd)
}
func (c *Chain) AddText(text string) {
text = strings.ToLower(text)
sentences := strings.Split(text, ".")
if sentences[len(sentences)-1] == "" {
sentences = sentences[:len(sentences)-1]
}
for i := range sentences {
sentence := strings.Split(sentences[i], " ")
if sentence[0] == "" {
sentence = sentence[1:]
}
c.AddSentence(sentence)
}
}
func (c *Chain) RandomSentence() string {
sentence := ""
lastWord := ChainStart
for {
var possibleWords []string
for word := range c.chain[lastWord] {
for i := 0; i < c.chain[lastWord][word]; i++ {
possibleWords = append(possibleWords, word)
}
}
rand.Shuffle(len(possibleWords), func(i, j int) {
possibleWords[i], possibleWords[j] = possibleWords[j], possibleWords[i]
})
selectedWord := rand.Intn(len(possibleWords))
if possibleWords[selectedWord] == ChainEnd {
sentence += "."
break
}
sentence += possibleWords[selectedWord] + " "
lastWord = possibleWords[selectedWord]
}
sentence = strings.Replace(sentence, " .", ".", -1)
return sentence
}