Jump to a problem, path or page
01 · Frame the problem
Choose one item with probability proportional to its nonnegative integer weight. This educational sampler is not intended for security-sensitive lotteries; the caller supplies a uniform bounded-integer random source.
Weighted sampling requires exact interval sizes over a uniform bounded draw. Analyse zero weights, integer overflow and the randomness adapter's contract before selecting a search structure.
02 · Find the design pressure
Begin with cumulative integer weights and binary search. Floating thresholds can blur boundaries, and modulo reduction can bias draws. Require an unbiased integer in the exact total range and select the first prefix strictly above it.
03 · Define success
04 · Identify the correctness boundary
Use checked integer prefix sums and draw uniformly from [0,totalWeight). Binary-search the first prefix strictly greater than the draw so zero-weight entries never win. The randomness adapter must guarantee unbiased bounded integers; applying modulo to an arbitrary random range can introduce bias.
05 · Make it concrete
Weights A=2, B=0 and C=3 produce prefixes 2,2,5. Draws 0 and 1 select A; draws 2 through 4 select C. B is never selected. An all-zero total is rejected rather than returning an arbitrary item or attempting an empty random range.
Jump to a problem, path or page