Generate random integers with probabilities

前端 未结 5 847
离开以前
离开以前 2020-11-30 02:27

I\'m a bit confused about how to generate integer values with probabilities.

As an example, I have four integers with their probability values: 1|0.4, 2|0.3, 3|0.2,

5条回答
  •  难免孤独
    2020-11-30 03:15

    This is the solution i find the most flexible, for picking within any set of object with probabilities:

    // set of object with probabilities:
    const set = {1:0.4,2:0.3,3:0.2,4:0.1};
    
    // get probabilities sum:
    var sum = 0;
    for(let j in set){
        sum += set[j];
    }
    
    // choose random integers:
    console.log(pick_random());
    
    function pick_random(){
        var pick = Math.random()*sum;
        for(let j in set){
            pick -= set[j];
            if(pick <= 0){
                return j;
            }
        }
    }

提交回复
热议问题