Sanskar Tiwari
IndianAppGuy Blog

IndianAppGuy Blog

Generate random integers with probabilities

Sanskar Tiwari's photo
Sanskar Tiwari
·Jul 1, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

So i am working on spinwheelpopups.com and i needed to find a way to give customer option so they can set the probability of a slice getting selecting when the wheel will spin

Code:

// 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;
        }
    }
}

source: https://stackoverflow.com/questions/8877249/generate-random-integers-with-probabilities

How i used

first create set of object with probabilities

const set = { 1: 0.4, 2: 0.3, 3: 0.2, 4: 0.1 };

So i did not had this directly so i went through the my array of map which contains the chance value for each slice now since i do not limit the total to be 100 customer might have entered the total of chances to be more than 100 hence i got the total first

Then i created a map and var and got the total

const spinSet = new Map();
var totalProb = 0;
for (let i = 0; i < responseStringifyJson.spin_options.length; i++) {
        totalProb =
          totalProb + parseInt(responseStringifyJson.spin_options[i].chance);
      }

Next i went through the array again and this time generated the set

for (let i = 0; i < responseStringifyJson.spin_options.length; i++) {
        var percentage =
          responseStringifyJson.spin_options[i].chance / totalProb;
        // only add if more than 0
        if (Number(parseFloat(percentage).toFixed(2)) != 0) {
          var percentageforthis = Number(parseFloat(percentage).toFixed(2));
          var key = i + 1;
          spinSet[key] = percentageforthis;
        }
      }

Then Just get probabilities sum and choose a random integer from the spinSet

 
Share this