Suppose I have an array
var list = ['a', 'b', 'c', 'd'];
and I want to select one value from List at random. If it is completely random, each will have a 25% chance. Is there a way to select a value at random with a bias like so:
var bias = [0.1, 0.2, 0.1, 0.6];
(bias of course adds up to 1)
So 'a' has a 10% chance of being selected and 'b' has a 20% chance of being selected, etc
Edit: I know I can just modify do var list = ['a', 'b', 'b', 'c', 'd', 'd', 'd', 'd', 'd', 'd'] and just select a value at random but I am looking for a more efficient way of doing this by just having an array that contains the bias.
Make a cumulative bias list:
var sum = 0;
var cumulativeBias = bias.map(function(x) { sum += x; return sum; });
Then make a random number from 0 to the sum (i.e. cumulativeBias[cumulativeBias.length - 1]):
var choice = Math.random() * sum;
Then search for the first element in cumulativeBias that is bigger than choice. You can use binary search for speed, but for short lists a sequential search is good enough. The index of that element is the chosen index. For example, something like:
var chosenIndex = null;
cumulativeBias.some(function(el, i) {
return el > choice ? ((chosenIndex = i), true) : false;
});
chosenElement = list[chosenIndex];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With