Sha256: f763a9e50ea5818ea233fe1db916c8b4d8e7a0f812217c9ade947cfbf3214e55
Contents?: true
Size: 1 KB
Versions: 1
Compression:
Stored size: 1 KB
Contents
# frozen_string_literal: true require 'weighted_list/normalizer' require 'weighted_list/version' require 'weighted_list/sampler' class WeightedList include Enumerable def self.[](collection) new(collection) end def initialize(collection) @hash = Normalizer.call(collection.clone) end def each(&block) hash.keys.each(&block) end def sample(quantity = nil, random: Random, with_replacement: false) return select_item(hash, random: random).selected unless quantity quantity.times.each_with_object(initial_memo) do |_index, memo| result = select_item(memo[:current_list], random: random) return memo[:selected] if result.selected.nil? memo[:selected].push(result.selected) memo[:current_list] = (with_replacement ? hash : result.remaining) end[:selected] end private attr_reader :hash, :random def initial_memo { selected: [], current_list: hash } end def select_item(list, random:) Sampler.new(hash: list, random: random).call end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
weighted_list-0.5.0 | lib/weighted_list.rb |