Skip to content

Instantly share code, notes, and snippets.

@rickw
Created May 12, 2009 17:00
Show Gist options
  • Save rickw/110596 to your computer and use it in GitHub Desktop.
Save rickw/110596 to your computer and use it in GitHub Desktop.
a weighted random method
#
# a weighted random
#
the_list = { "five" => 5, "three" => 3, "one" => 1 }
result_hash = { "five" => 0, "three" => 0, "one" => 0 }
count = 3
def weighted_random(list, count)
weighted_list = []
list.each do |key, val|
val.times do
weighted_list << key
end
end
result = []
count.times do
result << weighted_list[rand(weighted_list.length)]
end
result
end
all_results = []
1000.times do
all_results << weighted_random(the_list, count)
end
all_results.flatten.each { |v| result_hash[v] += 1 }
puts result_hash.inspect
puts "three to one ratio = #{result_hash[:three.to_s] / result_hash[:one.to_s]}"
puts "five to one ratio = #{result_hash[:five.to_s] / result_hash[:one.to_s]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment