Created
November 28, 2014 17:17
-
-
Save mickey/9073d274220e8684047a to your computer and use it in GitHub Desktop.
WeightedSampler -> Randoms with weight
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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