I am after some help trying to get my head around the logic needed to generate a random number based on 3 different probabilities.
My example is this:
I have an array of objects. Upon each cycle, this array can change in size (some objects added, some removed). Each object has a property called Priority
which is set to either High, Medium or Low.
I need an algorithm to pick a random object from the array but based on the Priority
. So objects with a High priority will have a higher probability of getting picked than objects with a Low priority.
I took this approach, manually creating an IndexArray and adding the index multiple times based on the priority each cycle and then picking a random index. So, for example:
switch( campaign.Priority ) {
// For high priority campaigns, probability is 6 out of 10
case 'High':
for( let i = 0; i < 6; i++ ) {
randomCampaignArray.push( idx );
}
break;
// For medium priority campaigns, probability is 3 out of 10
case 'Medium':
for( let i = 0; i < 3; i++ ) {
randomCampaignArray.push( idx );
}
break;
// For low priority campaigns, probability is 1 out of 10
case 'Low':
for( let i = 0; i < 1; i++ ) {
randomCampaignArray.push( idx );
}
break;
}
// Determine a random index from the campaign array
let index = Math.floor( Math.random() * randomCampaignArray.length );
// Get a handle to that indexed campaign
_campaign = campaigns[randomCampaignArray[index]];
But then I am left with an Array that looks like [1,1,1,1,1,1,2,2,2,3,3,3,4]
which then requires the random value to always be in the low range.
Is there a better and more practical approach to this?