Weighted random selection from array

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

    "Wheel of Fortune" O(n), use for small arrays only:

    function pickRandomWeighted(array, weights) {
        var sum = 0;
        for (var i=0; i

提交回复
热议问题