`
orcl_zhang
  • 浏览: 246500 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

ruby cookbook -- Choosing Randomly from a Weighted List

    博客分类:
  • ruby
阅读更多
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:
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

很聪明的做法
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics