Class: Markov::Statistics::RandomEvent

Inherits:
Object
  • Object
show all
Defined in:
lib/markov/statistics/random_event.rb

Instance Method Summary collapse

Constructor Details

#initialize(outcome_counts = {}) ⇒ RandomEvent

Returns a new instance of RandomEvent.



4
5
6
# File 'lib/markov/statistics/random_event.rb', line 4

def initialize(outcome_counts = {})
  @outcome_counts = outcome_counts
end

Instance Method Details

#add_outcome(outcome, count) ⇒ Object



8
9
10
# File 'lib/markov/statistics/random_event.rb', line 8

def add_outcome(outcome, count)
  @outcome_counts[outcome] = count
end

#normalized_outcome_probabilitiesObject



12
13
14
15
# File 'lib/markov/statistics/random_event.rb', line 12

def normalized_outcome_probabilities
  total_outcome_counts = @outcome_counts.values.reduce(:+).to_f
  @outcome_counts.map { |outcome, count| [outcome, count / total_outcome_counts] }.to_h
end

#predict!Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/markov/statistics/random_event.rb', line 17

def predict!
  roll = rand
  selected = nil
  normalized_outcome_probabilities.inject(0.0) do |acc, (outcome, probability)|
    if (acc += probability) > roll
      selected = outcome 
      break
    end
    acc
  end
  selected
end