Weighted random selection from array

后端 未结 13 1872
醉酒成梦
醉酒成梦 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:30

    The algorithm is straight forward

    rand_no = rand(0,1)
    for each element in array 
         if(rand_num < element.probablity)
              select and break
         rand_num = rand_num - element.probability
    

提交回复
热议问题