markov.go: a few changes

This commit is contained in:
Andreas Neue 2016-11-27 00:34:25 +01:00
parent abdab70ce1
commit 4388bc22b8
1 changed files with 33 additions and 20 deletions

View File

@ -187,34 +187,47 @@ func (c *MarkovChain) Generate(n int, in string) string {
} }
c.mu.Lock() c.mu.Lock()
defer c.mu.Unlock() defer c.mu.Unlock()
p := make(MarkovPrefix, c.prefixLen) var p MarkovPrefix
p = strings.Split(in, " ")
if len(p) > c.prefixLen {
i := rand.Intn(len(p) - 1)
p = p[i : i+c.prefixLen]
}
prefix := p.String()
xlog.Debug("Looking for answer on [%s]", prefix)
var words []string var words []string
for i := 0; i < n; i++ { var start string
choices := c.MarkovChain[p.String()] for attempt := 0; attempt < 10; attempt++ {
if len(choices) == 0 { /*
p = make(MarkovPrefix, c.prefixLen)
p = strings.Split(in, " ")
if len(p) > c.prefixLen {
i := rand.Intn(len(p) - 2)
p = p[i : i+c.prefixLen]
}
*/
p = make(MarkovPrefix, 1)
inWords := strings.Split(in, " ")
start = inWords[rand.Intn(len(inWords))]
p[0] = start
//ss = p.String()
xlog.Debug("Looking for answer on [%s]", start)
for i := 0; i < n; i++ {
choices := c.MarkovChain[p.String()]
if len(choices) == 0 {
break
}
next := choices[rand.Intn(len(choices))]
words = append(words, next)
if strings.HasSuffix(next, ".") || strings.HasSuffix(next, "!") || strings.HasSuffix(next, "?") {
break
}
p.Shift(next)
}
if len(words) > 0 {
break break
} }
next := choices[rand.Intn(len(choices))]
words = append(words, next)
if strings.HasSuffix(next, ".") || strings.HasSuffix(next, "!") || strings.HasSuffix(next, "?") {
break
}
p.Shift(next)
} }
prefix = strings.Trim(prefix, " ") start = strings.Trim(start, " ")
if len(words) == 0 { if len(words) == 0 {
xlog.Debug("No answer found") xlog.Debug("No answer found")
return prefix + " ... pfrrrz" return start + " ... pfrrrz"
} else { } else {
xlog.Debug("Found words: [%s]", strings.Join(words, " ")) xlog.Debug("Found words: [%s]", strings.Join(words, " "))
return prefix + " " + strings.Join(words, " ") return start + " " + strings.Join(words, " ")
} }
} }