Skip to content

Instantly share code, notes, and snippets.

@mickey
Created November 28, 2014 17:17
Show Gist options
  • Save mickey/9073d274220e8684047a to your computer and use it in GitHub Desktop.
Save mickey/9073d274220e8684047a to your computer and use it in GitHub Desktop.
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