Class: MoreMarkov::MarkovChainGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/more_markov.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

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

#frequenciesObject

Returns the value of attribute frequencies.



14
15
16
# File 'lib/more_markov.rb', line 14

def frequencies
  @frequencies
end

#sequencedObject

Returns the value of attribute sequenced.



14
15
16
# File 'lib/more_markov.rb', line 14

def sequenced
  @sequenced
end

#textObject

Returns the value of attribute text.



14
15
16
# File 'lib/more_markov.rb', line 14

def text
  @text
end

#wordsObject

Returns the value of attribute words.



14
15
16
# File 'lib/more_markov.rb', line 14

def words
  @words
end

Instance Method Details

#find_patternsObject



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