Sha256: 0306b0d8b97bf32845a27290a126a16fc8f64076e29454e24a5eb1d9d74122da
Contents?: true
Size: 740 Bytes
Versions: 1
Compression:
Stored size: 740 Bytes
Contents
require "roulette-wheel-selection/version" class RouletteWheelSelection class << self def sample(*args) object = args.first case object when Array ; sample_from_array(*args) when Hash ; sample_from_hash(*args) else ; fail "Unsupported type: #{object.class}" end end private def sample_from_array(array, key) hash = array.map{|v| [v, v[key]] }.to_h return sample_from_hash(hash) end def sample_from_hash(hash) total_rate = hash.values.inject(&:+) || 0 return if total_rate == 0 random_seed = rand(total_rate) hash.each do |obj, rate| return obj if random_seed < rate random_seed -= rate end end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
roulette-wheel-selection-1.0.1 | lib/roulette-wheel-selection.rb |