Generate random integers with probabilities

Headshota picture Headshota · Jan 16, 2012 · Viewed 21k times · Source

I'm a bit confused about how to generate integer values with probabilities.

As an example, I have four integers with their probability values: 1|0.4, 2|0.3, 3|0.2, 4|0.1

How can I generate these four numbers taking into account their probabilities?

Answer

Sergio Tulentsev picture Sergio Tulentsev · Jan 16, 2012

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