Class: Planout::WeightedChoice

Inherits:
OpRandom show all
Defined in:
lib/planout/weighted_choice.rb

Constant Summary

Constants inherited from OpRandom

OpRandom::LongScale

Instance Attribute Summary

Attributes inherited from Operator

#args

Instance Method Summary collapse

Methods inherited from OpRandom

#get_hash, #get_uniform, #get_unit

Methods inherited from OpSimple

#execute

Methods inherited from Operator

#execute, #initialize

Constructor Details

This class inherits a constructor from Planout::Operator

Instance Method Details

#simple_executeObject



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/planout/weighted_choice.rb', line 5

def simple_execute
  choices = @parameters[:choices]
  weights = @parameters[:weights]

  return [] if choices.length() == 0

  cum_weights = choices.zip(weights)
  cum_sum = 0.0

  cum_weights.each do |choice, weight|
    cum_sum += weight
    cum_weights[choice] = cum_sum
  end

  stop_value = get_uniform(0.0, cum_sum)

  cum_weights.each do |choice, cum_weight|
    choice if stop_value <= cum_weight
  end
end