Sha256: b61f22d63496593fd34aa0afd574fd05c80374b24979fce576f7c2019a97ae97

Contents?: true

Size: 782 Bytes

Versions: 8

Compression:

Stored size: 782 Bytes

Contents

module Markov
  module Statistics
    class RandomEvent
      def initialize(outcome_counts = {})
        @outcome_counts = outcome_counts
      end

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

      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

      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
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
markov-rb-0.1.9 lib/markov/statistics/random_event.rb
markov-rb-0.1.8 lib/markov/statistics/random_event.rb
markov-rb-0.1.7 lib/markov/statistics/random_event.rb
markov-rb-0.1.6 lib/markov/statistics/random_event.rb
markov-rb-0.1.5 lib/markov/statistics/random_event.rb
markov-rb-0.1.4 lib/markov/statistics/random_event.rb
markov-rb-0.1.3 lib/markov/statistics/random_event.rb
markov-rb-0.1.2 lib/markov/statistics/random_event.rb