class MoreMarkov::MarkovChainGenerator
Attributes
frequencies[RW]
sequenced[RW]
text[RW]
words[RW]
Public Class Methods
new(text)
click to toggle source
# File lib/more_markov.rb, line 16 def initialize(text) @text = text @words = text.split @frequencies = {} @sequenced = false end
Public Instance Methods
find_patterns()
click to toggle source
# File lib/more_markov.rb, line 23 def find_patterns @words.each_with_index do |word, index| if index < (@words.length - 1) if !@frequencies.include?(word) @frequencies[word] = {} @frequencies[word][@words[index + 1]] = 1 elsif !@frequencies[word].include?(@words[index + 1]) @frequencies[word][@words[index + 1]] = 1 else @frequencies[word][@words[index + 1]] += 1 end end end @sequenced = true end
generate_chain(word_count, start = nil)
click to toggle source
# File lib/more_markov.rb, line 39 def generate_chain(word_count, start = nil) warning_a = "Please run the instance method 'find_patterns' first to build the generator's dictionary." warning_b = "The start word that you have provided does not appear in the text used to build this generator." chain = "" return warning_a if @sequenced == false start = @words.sample if start == nil return warning_b if !@words.include?(start) chain += start word_count.times do chain += " " probabilities = @frequencies[start] next_word = MoreMarkov.weighted_choice(probabilities) chain += next_word start = next_word end chain end