Resource 路 Guide or article
Weighted Random
Shows how to pick an item from a list at random while respecting per-item weights, using a fruit-and-vegetable example with weights 3, 7 and 1. Useful for anyone who knows basic JavaScript arrays and wants a clear model of cumulative-weight sampling.
Reviewed
Open the original: Weighted Random (opens the original site in a new tab)Add to a roadmap
Keep this resource with a roadmap you follow. It appears as your own extra resource; the roadmap's steps don't change and it doesn't count toward your tracked steps.
Source content: English
Let's say you have a list of items. Item could be anything. For example, we may have a list of fruits and vegetables that you like to eat: [ '馃崒', '馃崕', '馃' ]. The list of weights represent the weight (or probability, or importance) of each item. Weights are numbers. For example, the weights like [3, 7, 1] would say that: The Weighted Random in this case will be the function that will randomly return you the item from the list, and it will take each item's weight into account, so that items with the higher weight will be picked more often.
PrepKit overview
PrepKit editors wrote and reviewed this overview from the source repository. It is not text from the resource itself.
- Suited to
- The source does not state a level
- Format
- Lesson
What it covers
- Defines items and weights and shows the expected function interface
- Explains the naive approach of repeating items by weight and why it can waste memory
- Builds the cumulative weights array and maps a random number to the first bucket that covers it
- Includes a full JavaScript weightedRandom function with input checks
- Lists uses in genetic algorithm selection, RNN text generation and Nginx load balancing
How to use it
PrepKit study advice, not a claim made by the source.
Rewrite the selection loop as a binary search over the cumulative weights, then run each version many times and compare the observed frequencies with the weights. You are done when you can explain why heavier items take up more of the numeric range.
Scope and limitations
Gives no formal complexity analysis and does not discuss the binary-search refinement. The application examples link to the author's own blog post and notebook. Code is JavaScript only.
Access and format
README on GitHub in trekhleb/javascript-algorithms (MIT); it links to the folder's weightedRandom.js and its test file. English, free.
Reviewed by PrepKit on Oct 2, 2026. Listing source commit: 85293e3e2b88
Evidence behind this overview
- src/algorithms/statistics/weighted-random/README.md
Pages that include this
Get the PrepKit newsletter
Optional. You don't need it to use PrepKit.