How to Generate Weighted Random Numbers
Random numbers usually follow what we call a ‘uniform distribution’, meaning that there is the same chance that any of the numbers is picked.
But if you want some numbers to be picked more often than others you will need a different strategy: a weighted random number generator.
Some practical applications include:
- the loot table in a video game, where enemies can drop different items with varying drop rates.
- a raffle, where people with more tickets have more chances to win.
If you think about the raffle example you can come up with an obvious solution: generate an array which has one copy of the item for each ‘ticket’.
For example, if John buys 4 raffle tickets and David only buys 1, John will have 4 times more chances to win than David.
Here is a working implementation:
I’m adding the person’s name once for every ticket they bought, and then I pick a random name from that list. By virtue of being on the list more times, it will increase the chances of that name being picked.
I like this approach because it’s very simple and once you have your list it’s very fast to pick a winner.
Sum of Weights
There is another way you can do this that is more memory-efficient, the trade-off is that picking a random value is slower.
The idea is to pick a random number between 1 and the sum of all the weights, and then loop until you find a weight that is lower or equal than this number.
Here is the code:
This code takes in a hash where the keys are the items and the values are the weights. You can call this method like this:
You can test if this works as expected by looking at the distribution of the results after running it many times.
Here is an example:
Run this a few times and look at the output to see if the ratio is what it should be.
While there are more sophisticated algorithms, these two should serve you well. I hope you found this article useful, please share it with your friends so I can keep writing more!Learn how to generate weighted random numbers in Ruby with some easy to implement algorithms.
Weighted Football Draft Order
- Aug 10, 2004
I’m hoping that someone can help me with this minor issue. We have a football draft every year and the first year we generated the draft order through a random number formula.
In year two we want to use a weighted random number based on the place that you finished the previous year. If we were to do this through ping pong balls in a box, the tenth place team would have 10 balls, ninth would have 9 balls and so on. Therefore the first place team could still get the first pick in the draft, but they would only have a one in fifty-five chance.I'm hoping that someone can help me with this minor issue. We have a football draft every year and the first year we generated the draft order through a… ]]>