Generate A Weighted Random Number

前端 未结 11 2219
予麋鹿
予麋鹿 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:50

    I have a slotmachine and I used the code below to generate random numbers. In probabilitiesSlotMachine the keys are the output in the slotmachine, and the values represent the weight.

    const probabilitiesSlotMachine         = [{0 : 1000}, {1 : 100}, {2 : 50}, {3 : 30}, {4 : 20}, {5 : 10}, {6 : 5}, {7 : 4}, {8 : 2}, {9 : 1}]
    var allSlotMachineResults              = []
    
    probabilitiesSlotMachine.forEach(function(obj, index){
        for (var key in obj){
            for (var loop = 0; loop < obj[key]; loop ++){
                allSlotMachineResults.push(key)
            }
        }
    });
    

    Now to generate a random output, I use this code:

    const random = allSlotMachineResults[Math.floor(Math.random() * allSlotMachineResults.length)]
    

提交回复
热议问题