Class: WeightedSampler::Base

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

Instance Method Summary collapse

Constructor Details

#initialize(enum, seed: nil, skip_normalization: false) ⇒ Base

Returns a new instance of Base.

Raises:

  • (ArgumentError)


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/weighted_sampler.rb', line 13

def initialize(enum, seed: nil, skip_normalization: false)
  @random = Random.new(seed) unless seed.nil?

  if enum.is_a?(Hash)
    @p_margins = normalized_margins(enum.values, skip_normalization)
    @keys = enum.keys
  elsif enum.is_a?(Array)
    @p_margins = normalized_margins(enum, skip_normalization)
    @keys = [*0...enum.size]
  end

  return unless @p_margins.nil? || @keys.nil? || @keys.empty?

  raise ArgumentError, 'input structure must be a non-empty Hash or Array'
end

Instance Method Details

#sampleObject



29
30
31
32
33
34
35
36
# File 'lib/weighted_sampler.rb', line 29

def sample
  pick = @random ? @random.rand : rand

  idx = @p_margins.find_index { |margin| pick < margin }
  idx ||= @p_margins.count - 1 # safe assignment if last margin was not good enough

  @keys[idx]
end