diff --git a/modules/markov.go b/modules/markov.go index c930300..ac07aa5 100644 --- a/modules/markov.go +++ b/modules/markov.go @@ -187,34 +187,47 @@ func (c *MarkovChain) Generate(n int, in string) string { } c.mu.Lock() defer c.mu.Unlock() - p := make(MarkovPrefix, c.prefixLen) - 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 p MarkovPrefix var words []string - for i := 0; i < n; i++ { - choices := c.MarkovChain[p.String()] - if len(choices) == 0 { + var start string + for attempt := 0; attempt < 10; attempt++ { + /* + 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 } - 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 { xlog.Debug("No answer found") - return prefix + " ... pfrrrz" + return start + " ... pfrrrz" } else { xlog.Debug("Found words: [%s]", strings.Join(words, " ")) - return prefix + " " + strings.Join(words, " ") + return start + " " + strings.Join(words, " ") } }