Weighted random selection from array

后端 未结 13 1867
醉酒成梦
醉酒成梦 2020-11-28 03:13

I would like to randomly select one element from an array, but each element has a known probability of selection.

All chances together (within the array) sums to 1.<

13条回答
  •  -上瘾入骨i
    2020-11-28 03:18

    Ruby solution using the pickup gem:

    require 'pickup'
    
    chances = {0=>80, 1=>20}
    picker = Pickup.new(chances)
    

    Example:

    5.times.collect {
      picker.pick(5)
    }
    

    gave output:

    [[0, 0, 0, 0, 0], 
     [0, 0, 0, 0, 0], 
     [0, 0, 0, 1, 1], 
     [0, 0, 0, 0, 0], 
     [0, 0, 0, 0, 1]]
    

提交回复
热议问题