Class: MoreMarkov::MarkovChainGenerator
- Inherits:
-
Object
- Object
- MoreMarkov::MarkovChainGenerator
- Defined in:
- lib/more_markov.rb
Instance Attribute Summary collapse
-
#frequencies ⇒ Object
Returns the value of attribute frequencies.
-
#sequenced ⇒ Object
Returns the value of attribute sequenced.
-
#text ⇒ Object
Returns the value of attribute text.
-
#words ⇒ Object
Returns the value of attribute words.
Instance Method Summary collapse
- #find_patterns ⇒ Object
- #generate_chain(word_count, start = nil) ⇒ Object
-
#initialize(text) ⇒ MarkovChainGenerator
constructor
A new instance of MarkovChainGenerator.
Constructor Details
#initialize(text) ⇒ MarkovChainGenerator
Returns a new instance of MarkovChainGenerator.
16 17 18 19 20 21 |
# File 'lib/more_markov.rb', line 16 def initialize(text) @text = text @words = text.split @frequencies = {} @sequenced = false end |
Instance Attribute Details
#frequencies ⇒ Object
Returns the value of attribute frequencies.
14 15 16 |
# File 'lib/more_markov.rb', line 14 def frequencies @frequencies end |
#sequenced ⇒ Object
Returns the value of attribute sequenced.
14 15 16 |
# File 'lib/more_markov.rb', line 14 def sequenced @sequenced end |
#text ⇒ Object
Returns the value of attribute text.
14 15 16 |
# File 'lib/more_markov.rb', line 14 def text @text end |
#words ⇒ Object
Returns the value of attribute words.
14 15 16 |
# File 'lib/more_markov.rb', line 14 def words @words end |
Instance Method Details
#find_patterns ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# 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) ⇒ Object
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# 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 |