Class: MonteCarlo::HistogramRandomPicker

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

Instance Method Summary collapse

Constructor Details

#initialize(histogram) ⇒ HistogramRandomPicker

histogram is a hash where the keys are the possible outcomes and the values are the number of occurrences of each outcome. For example, { 1 => 2, 2 => 3, 3 => 1 } means that the possible outcomes are 1, 2 and 3, and that 1 occurs twice, 2 occurs three times and 3 occurs once.



5
6
7
8
# File 'lib/montecarlo/histogram_random_picker.rb', line 5

def initialize(histogram)
  @histogram = histogram
  calculate_cumulative_occurrences!
end

Instance Method Details

#pickObject



10
11
12
13
14
# File 'lib/montecarlo/histogram_random_picker.rb', line 10

def pick
  random_number = rand(@total_occurrences)
  found_cumulative = @cumulative_occurrences.bsearch { |cumulative| random_number < cumulative[:cumulative] }
  found_cumulative[:throughput]
end