class LoadedDie::Sampler

Constants

DEFAULT_RNG
Segment

Public Class Methods

new(population) click to toggle source
# File lib/loaded_die.rb, line 12
def initialize(population)
  @compiled = population.inject [] do |accum, (individual, weight)|
    if weight <= 0
      raise ::ArgumentError, "non-positive weight #{weight}"
    end
    prev_max =
      if last = accum.last
        last.maximum
      else
        0
      end
    accum << Segment.new(prev_max + weight, individual)
  end
  nil
end

Public Instance Methods

[](point) click to toggle source
# File lib/loaded_die.rb, line 36
def [](point)
  if point < 0
    nil
  elsif choice = @compiled.detect { |segment| point < segment.maximum }
    choice.individual
  else
    nil
  end
end
length() click to toggle source
# File lib/loaded_die.rb, line 28
def length
  if last = @compiled.last
    last.maximum
  else
    0
  end
end
sample(options = {}) click to toggle source
# File lib/loaded_die.rb, line 46
def sample(options = {})
  rng = options.fetch(:random) { DEFAULT_RNG }
  point = rng.rand(length)
  self[point]
end