Skip to content

Instantly share code, notes, and snippets.

@jasonl99
Last active March 13, 2018 02:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonl99/25d3c922d73f10a75fe228c2de38d270 to your computer and use it in GitHub Desktop.
Save jasonl99/25d3c922d73f10a75fe228c2de38d270 to your computer and use it in GitHub Desktop.
Random Sample in Ruby
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