Class: MarkovChain
- Inherits:
-
Object
- Object
- MarkovChain
- Defined in:
- lib/markov_chain.rb
Defined Under Namespace
Modules: Prediction
Class Method Summary collapse
-
.from(data) ⇒ Object
datais #data() of the other MarkovChain.
Instance Method Summary collapse
-
#append!(states) ⇒ Object
appends
statesto the end of this MarkovChain. -
#data ⇒ Object
datapassed to MarkovChain.new() or MarkovChain.from(). -
#initialize(data = {}) ⇒ MarkovChain
constructor
creates an empty MarkovChain.
-
#predict ⇒ Object
returns Enumerable of predicted states.
Constructor Details
#initialize(data = {}) ⇒ MarkovChain
creates an empty MarkovChain.
data is a map which becomes owned by this MarkovChain.
17 18 19 20 |
# File 'lib/markov_chain.rb', line 17 def initialize(data = {}) @data = data @last_state = nil end |
Class Method Details
.from(data) ⇒ Object
data is #data() of the other MarkovChain. It becomes owned by the returned MarkovChain.
8 9 10 |
# File 'lib/markov_chain.rb', line 8 def self.from(data) new(data) end |
Instance Method Details
#append!(states) ⇒ Object
appends states to the end of this MarkovChain.
states is an Array of arbitrary objects.
It returns this (modified) MarkovChain.
29 30 31 32 33 34 35 36 37 38 |
# File 'lib/markov_chain.rb', line 29 def append!(states) for next_state in states state_occurences_map = (@data[@last_state] or Hash.new) state_occurences_map[next_state] ||= 0 state_occurences_map[next_state] += 1 @data[@last_state] = state_occurences_map @last_state = next_state end return self end |
#data ⇒ Object
data passed to MarkovChain.new() or MarkovChain.from().
58 59 60 |
# File 'lib/markov_chain.rb', line 58 def data @data end |
#predict ⇒ Object
returns Enumerable of predicted states. The states are predicted by states passed to #append!().
The result may contain nils. Each nil means that MarkovChain could not predict a state after the one before nil. Example:
markov_chain.predict().take(4) #=> ["a", "c", "b", nil]
That means markov_chain could not predict a state after “b”.
51 52 53 |
# File 'lib/markov_chain.rb', line 51 def predict() self.extend(Prediction) end |