Sometimes, we want to generate random integers with probabilities with JavaScript.
In this article, we’ll look at how to generate random integers with probabilities with JavaScript.
How to generate random integers with probabilities with JavaScript?
To generate random integers with probabilities with JavaScript, we can define an array with the possible items that we want to generate with their number of occurrences weighted by their probability.
Then we can use Math.random
to pick from the array.
For instance, we write:
const randomWithProbability = () => {
const notRandomNumbers = [1, 1, 1, 1, 2, 2, 2, 3, 3, 4];
const idx = Math.floor(Math.random() * notRandomNumbers.length);
return notRandomNumbers[idx];
}
console.log(randomWithProbability())
to define the randomWithProbability
function.
In it, we have notRandomNumbers
which we draw numbers from.
Then we have
const idx = Math.floor(Math.random() * notRandomNumbers.length);
to return the number index idx
of the number we draw.
Conclusion
To generate random integers with probabilities with JavaScript, we can define an array with the possible items that we want to generate with their number of occurrences weighted by their probability.