Last active
March 13, 2018 02:36
-
-
Save jasonl99/25d3c922d73f10a75fe228c2de38d270 to your computer and use it in GitHub Desktop.
Random Sample in Ruby
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 Demo | |
EXAMPLE = { "75%" => 0.75, "15%" => 0.15, "9%" => 0.09, "1%" => 0.01 } | |
def self.sample(choices = EXAMPLE) | |
choices.max_by { |_, weight| rand ** (1.0 / weight) }.first | |
end | |
def self.show(samples: 10000) | |
items = samples.times.map {sample} | |
items.each_with_object(Hash.new(0)) do |item, counts| | |
counts[item]+=1 | |
end.sort_by(&:last).reverse.to_ h | |
end | |
end | |
# Demo.show | |
# => {"75%"=>7480, "15%"=>1525, "9%"=>901, "1%"=>94} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment