Weighted random selection from array

后端 未结 13 1916
醉酒成梦
醉酒成梦 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条回答
  •  悲&欢浪女
    2020-11-28 03:23

    An example in ruby

    #each element is associated with its probability
    a = {1 => 0.25 ,2 => 0.5 ,3 => 0.2, 4 => 0.05}
    
    #at some point, convert to ccumulative probability
    acc = 0
    a.each { |e,w| a[e] = acc+=w }
    
    #to select an element, pick a random between 0 and 1 and find the first   
    #cummulative probability that's greater than the random number
    r = rand
    selected = a.find{ |e,w| w>r }
    
    p selected[0]
    

提交回复
热议问题