Categories:

Generating weighed random numbers in JavaScript

While it's impossible to forecast the exact occurrence of a random event, even a non-mathematician would agree we can manipulate the likelihood of something occurring. For example, in the case of winning the lottery, that would simply mean buying more tickets (and having your dreams dashed multiple times of course). In this tutorial, we take a stab at generating weighed random numbers, or random numbers with some more likely to show up than others. This is useful in situations where you need a more refined random engine, for example in a banner script that can display some banners more often than others. 

Lets begin by looking back. As discussed in this tutorial, to generate a random number in JavaScript, the code:

var randomnumber=Math.floor(Math.random()*11)

will do nicely, whereby a random number between 0 to 10 is generated.

Increasing the odds

When we talk about manipulating the chances of a particular number popping up, first of all, it must be relative to some other numbers. This may seem obvious, but important to establish nevertheless. Even in the above example, there is an implied set of numbers, namely, 1 to 10, with the odds of each one getting picked being equal. Putting a weight on a number means changing this "equality."