class MTK::Patterns::Choice
Randomly choose from a list of elements.
Supports giving different weights to different choices. Default is to weight all choices equally.
Public Class Methods
new(elements, options={})
click to toggle source
@param (see Pattern#initialize) @option (see Pattern#initialize) @option options [Array] :weights a list of chances that each corresponding element will be selected (normalized against the total weight) @example choose the second element twice as often as the first or third:
MTK::Pattern::Choice.new [:first,:second,:third], :weights => [1,2,1]
Calls superclass method
# File lib/mtk/patterns/choice.rb, line 16 def initialize(elements, options={}) super @weights = options.fetch :weights, Array.new(@elements.length, 1) @total_weight = @weights.inject(:+).to_f end
Protected Instance Methods
advance()
click to toggle source
# File lib/mtk/patterns/choice.rb, line 25 def advance @index += 1 raise StopIteration if @index > 0 target = rand * @total_weight @weights.each_with_index do |weight,index| if target < weight @current = @elements[index] break else target -= weight end end end