Generate A Weighted Random Number

前端 未结 11 2351
予麋鹿
予麋鹿 2020-11-22 12:40

I\'m trying to devise a (good) way to choose a random number from a range of possible numbers where each number in the range is given a weight. To put it simply: given the

11条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 12:56

    I suggest to use a continuous check of the probability and the rest of the random number.

    This function sets first the return value to the last possible index and iterates until the rest of the random value is smaller than the actual probability.

    The probabilities have to sum to one.

    function getRandomIndexByProbability(probabilities) {
        var r = Math.random(),
            index = probabilities.length - 1;
    
        probabilities.some(function (probability, i) {
            if (r < probability) {
                index = i;
                return true;
            }
            r -= probability;
        });
        return index;
    }
    
    var i,
        probabilities = [0.8, 0.1, 0.1],
        count = probabilities.map(function () { return 0; });
    
    for (i = 0; i < 1e6; i++) {
        count[getRandomIndexByProbability(probabilities)]++;
    }
    
    console.log(count);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题