Class: WeightedRandomizer

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

Overview

Note:

Mostly adapted from recipe 5.11 from the Ruby Cookbook.

Implements weighted randomization for a group of weighted items. This class expects a hash of key -> value pairs where the value is the weight for the item.

Examples:

Usage

wr = WeightedRandomizer.new('queue1' => 25, 'queue2' => 100, 'queue3' => 2)
puts "Using queue #{wr.sample}"

Constant Summary collapse

VERSION =
'0.1.2'

Instance Method Summary collapse

Constructor Details

#initialize(items) ⇒ WeightedRandomizer

Creates a new instance.

Parameters:

  • items (Hash)

    the weighted items (key item, value weight)



17
18
19
# File 'lib/weighted_randomizer.rb', line 17

def initialize(items)
  @items = normalize(items)
end

Instance Method Details

#sample(num = nil) ⇒ Object+

Returns one or more weighted random values.

Parameters:

  • num (Integer) (defaults to: nil)

    the number of samples to return

Returns:

  • (Object, Array<Object>)

    one or more sampled items



25
26
27
28
# File 'lib/weighted_randomizer.rb', line 25

def sample(num = nil)
  return _sample unless num
  Array.new(num) { _sample }
end