Recipe 5.11. Choosing Randomly from a Weighted List
Store the elements in a hash, mapped to their relative probabilities. The following code will work with a hash whose keys are mapped to relative integer probabilities:
很聪明的做法
Store the elements in a hash, mapped to their relative probabilities. The following code will work with a hash whose keys are mapped to relative integer probabilities:
def choose_weighted(weighted)
sum = weighted.inject(0) do |sum, item_and_weight|
sum += item_and_weight[1]
end
target = rand(sum)
weighted.each do |item, weight|
return item if target <= weight
target -= weight
end
end
很聪明的做法