You can find a video version of this article on my YouTube Channel.
Intro
Today we're building together a weighted random generator. You may also know it as a random loot table generator, or gacha system.
In short, what it does is extract a random object considering its weight. An object with a higher weight is more likely to be picked up than an item with a smaller weight (or call it chance).
As a side quest, we're going to keep code coverage at 100% โ
Output
The final result is already available on GitHub (there are open issues to pick up!).
You can also install it from npm and deno.
If you're on node, you can install it with npm i wrand
and you can use it like so:
const picker = new RandomPicker(items);
const result = picker.pick();
const results = picker.pickMany(3);
Development
As seen in the preview, we're going to build a generator (with a class) that takes an array of objects in the constructor and will spit out randomly picked items with two methods: pick
and pickMany
.
Typing
As we're in Typescript, let's start by giving a type definition to our input.
Our type will have two fields, one to keep the original items we passed in, and the other to store its weight (or chance, probability).
A heavier weight means more likely to be picked up.
Core class
To add some more informative content, we'll build this up with a little bit of Test Driven Development (TDD).
We can create a new file, randomGenerator.ts with the skeleton of the final product.
Before writing the implementation, we have to write the tests! This approach helps write code that is more reliable and with fewer bugs as you focus on the business logic first, and only after that on the implementation.
In this case, I'm using Jest, so npm i jest
to have it running.
In my tests, I want to make sure that:
- The class is instantiated properly.
- A random item is picked and comes from my list.
- N random items are picked, exactly the amount I requested and all of them are in the list.
- Works not only with strings but also with objects.
Note: To improve the tests even more, there's an open issue about passing a custom random generator. This could allow to set a generator with a specific seed (Math.random can't do that) and make the tests predictable, rather than entirely random.
Now that the tests are written, we can proceed with the implementation.
If we run the test now, they're all green and 100% code coverage โ
Validation
Let's add some validation to our input. As usual, tests first!
This time we want to check that:
- The list is not empty
- There are no duplicates
- There are no negative weights
Tests are looking good, we can implement the validation method.
npm run test
and it's all green and 100% again! โ
Standalone
With the current implementation, to pick one item only you need to explicitly create the RandomGenerator
instance and call pick
on it.
As we're building a library, it might be useful to also provide some standalone methods that do everything under the hood so that one can directly call pick
or pickMany
without seeing the logic behind it.
Going further
The core implementation is done and the requested functionalities described at the beginning are already working.
As I mentioned, the library is Open Source and the code is available on GitHub. I'm repeating it because this means it's open to contributions and for example, you're free to pick up some of the open issues.
In the meantime, the library has been extended with more utility methods (getItems
, getWeights
, getTotalWeight
, getCount
) and also an extra standalone method to flatten
the items in case you have duplicates and you want to aggregate their weights.
Feel free to jump on GitHub and extend it, even more, I'm waiting for your Pull Requests! :)
Thanks for reading this post, I hope you find it interesting!
Feel free to follow me to get notified when new articles are out ;)
You can also follow me on your favourite platform!
Top comments (3)
Hi, Leonardo. Thanks for the article. What do you think there is the way to pick an item without iterating over the internal array?
Hei Andrei, sure you can!
A different approach is to create an array of N items where N is the sum of all weights. Each element of the array contains the reference of one of your items.
For example if item A has weight 3, it will appear 3 times on that array, item B has weight 2, will appear twice.
Your array now has 5 elements: 3 times item A and 2 times item B, order does not matter.
From that point, just pick a random number from 0 to N-1 and ta-da, you have the index of the second array and your random item in O(1).
Let me know if the explanation is understandable, otherwise I can create a quick demo ๐
Really enjoyed reading this it's a nice write-up.