Generate random integers with probabilities
Here's a useful trick :-)
function randomWithProbability() {
var notRandomNumbers = [1, 1, 1, 1, 2, 2, 2, 3, 3, 4];
var idx = Math.floor(Math.random() * notRandomNumbers.length);
return notRandomNumbers[idx];
}
A simple naive approach can be:
function getRandom(){
var num=Math.random();
if(num < 0.3) return 1; //probability 0.3
else if(num < 0.6) return 2; // probability 0.3
else if(num < 0.9) return 3; //probability 0.3
else return 4; //probability 0.1
}
More flexible solution based on @bhups answer. This uses the array of probability values (weights). The sum of 'weights' elements should equal 1.
var weights = [0.3, 0.3, 0.3, 0.1]; // probabilities
var results = [1, 2, 3, 4]; // values to return
function getRandom () {
var num = Math.random(),
s = 0,
lastIndex = weights.length - 1;
for (var i = 0; i < lastIndex; ++i) {
s += weights[i];
if (num < s) {
return results[i];
}
}
return results[lastIndex];
};