-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmchain.go
135 lines (108 loc) · 2.24 KB
/
mchain.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package mctext
import (
"bufio"
"io"
"math/rand"
"strings"
"time"
)
type MChain struct {
Nodes map[string]*Node
}
func init() {
rand.Seed(time.Now().UnixNano())
}
func New() *MChain {
return &MChain{
Nodes: map[string]*Node{},
}
}
func (mc *MChain) Parse(in io.Reader) {
wordScanner := bufio.NewScanner(in)
wordScanner.Split(bufio.ScanWords)
var pos int
var last *Node
for wordScanner.Scan() {
word := strings.ToLower(wordScanner.Text())
word = strings.Trim(word, "-()[]{}\"'")
if strings.ContainsAny(word, "0123456789[](){}\"'-+/*%$") {
// filter some unwanted words
continue
}
if n, ok := mc.Nodes[word]; ok {
if pos > 0 {
last.AddNext(n)
last = n
}
} else {
newNode := &Node{
value: word,
children: []*Node{},
counts: map[string]int64{},
weights: []float64{},
}
mc.Nodes[word] = newNode
if pos > 0 {
last.AddNext(newNode)
}
last = newNode
}
pos++
}
mc.generateWeights()
}
func (mc *MChain) Generate(start string, length int) string {
rand.Seed(time.Now().UnixNano())
return strings.Join(mc.GenerateSlice(start, length), " ")
}
func (mc *MChain) GenerateSlice(start string, length int) []string {
var root *Node
if n, ok := mc.Nodes[start]; ok {
root = n
} else {
for _, node := range mc.Nodes {
root = node
break
}
}
return root.Generate([]string{}, int(length))
}
func (mc *MChain) generateWeights() {
for _, n := range mc.Nodes {
for _, nn := range n.children {
n.weights = append(n.weights, float64(n.counts[nn.value])/float64(n.totalCount))
}
}
}
type Node struct {
value string
children []*Node
counts map[string]int64
weights []float64
totalCount int64
}
func (n *Node) AddNext(nn *Node) {
if _, ok := n.counts[nn.value]; !ok {
n.children = append(n.children, nn)
}
n.counts[nn.value]++
n.totalCount++
}
func (n *Node) Generate(res []string, length int) []string {
if len(res) == length || len(n.children) == 0 {
return res
}
res = append(res, n.value)
return n.Next().Generate(res, length)
}
func (n *Node) Next() *Node {
num := rand.Float64()
var wSum float64
for i, w := range n.weights {
wSum += w
if num < wSum {
return n.children[i]
}
}
return n.children[len(n.children)-1]
}