Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WeightedSampler -> Randoms with weight
class WeightedSampler
def initialize(items)
@items = normalize(items)
end
def sample(num = nil)
return get_sample unless num
Array.new(num) { get_sample }
end
private
def get_sample
pick = rand()
@items.each do |key, weight|
return key if pick <= weight
pick -= weight
end
nil
end
def normalize(items)
sum = items.values.inject(0.0, :+)
items.each_with_object({}) do |(key, weight), memo|
memo[key] = weight / sum
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment