AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |
Back to Blog
Weighted random list generator8/1/2023 We could just as easily have thrown together an array of objects, like, instead of an array of arrays. Splitting values in this manner helps keep code readable, and at scale, helps reduce code bloat. This allows us to say that "Apples" should be 10x more common than, say, "Dates", without us having to type "Apples" ten separate times into a flat array. Here we have an array of arrays, the inner ones containing a value in at the top followed by a weight. There is no Absolute Best Practice here, but ideally the solution should strike a balance between runtime performance and code readability. The first thing we'd need to do is decide how we want to format our data so that choices can have weight. This approach works perfectly well when all choices are weighted equally, but what if we want to treat some values as more likely than others? The Setup By multiplying this against the length of the array, then flooring the value to make sure we wind up with a proper integer, we have ourselves a random index. The lower boundary is inclusive, the upper boundary is exclusive (e.g. The Math.random() function returns a random float between 0.0 and 1.0. In Javascript, the simplest way to accomplish this would be something like: const randomIndex = Math.floor(Math.random() * arr.length) There are many circumstances in which you might wish to choose a random value from a fixed list of choices. Stuff Technical Blog (702) 608-2086 Randomizing Weighted Choices in Javascript
0 Comments
Read More
Leave a Reply. |