Weighted random selection from array
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Weighted random selection chooses an item with probability proportional to its weight instead of assigning equal chance to every item. This pattern is used in recommendation ranking, game rewards, load balancing, and simulation systems. A robust implementation needs correct probability math, input validation, and predictable behavior under repeated sampling. Choosing the right sampling strategy early prevents subtle fairness and probability bugs in production ranking systems.
Basic Cumulative-Weight Algorithm
The most practical method is cumulative weights plus binary search. Build prefix sums, draw one random number in total range, and locate the first prefix that exceeds the draw.
This method is easy to audit and works well for many services.
Build a Reusable Sampler Class
For production code, validate weights and precompute state once.
Using a class avoids rebuilding prefix sums for every call.
Validate Distribution Quality
Weighted randomness should be tested statistically, not by one or two picks.
Expected frequencies are roughly 0.2, 0.3, and 0.5. Small drift is normal, but large drift suggests a bug.
Performance Tradeoffs and Alternative Methods
Cumulative plus binary search gives:
- preprocessing time linear in item count
- draw time logarithmic in item count
- memory linear in item count
For very high-frequency draws with static weights, alias method can provide near constant-time sampling after heavier preprocessing. For frequently changing weights, cumulative method is often easier because rebuild cost is low and implementation risk is smaller.
Choose based on workload:
- stable weights and huge draw volume: alias method may win
- changing weights or moderate volume: cumulative method is usually best
Deterministic Testing and Reproducibility
Injecting a seeded random generator makes tests stable.
In analytics pipelines and experiments, seeded randomness is useful for repeatable comparisons between algorithm versions.
Dynamic Weight Updates
If weights change over time, you can rebuild sampler state when updates arrive.
Keep rebuild logic explicit so data errors such as negative scores are handled consistently.
Numerical Stability Notes
With extremely large or tiny floating-point weights, precision can degrade. Two common mitigations are:
- normalize weights relative to max value before building prefix sums
- use integer weights when natural counts are available
These steps are usually unnecessary for ordinary business scores, but they matter in simulation engines with wide value ranges.
Common Pitfalls
A frequent mistake is allowing negative or all-zero weights, which makes probability semantics invalid.
Another mistake is rebuilding cumulative arrays for every draw in a hot path. That destroys throughput.
A third mistake is asserting exact probability values in tiny test samples. Randomness needs large-run checks.
Teams also forget reproducible seeds during tests, leading to flaky pipelines and confusing failures.
Summary
- Weighted selection picks items proportional to their weights.
- Cumulative prefix sums plus binary search is a reliable baseline algorithm.
- Validate input weights and precompute sampler state for repeated draws.
- Use statistical checks and seeded tests to verify correctness.
- Match algorithm choice to workload profile and update frequency.

