Math Fundamentals18 sections · 814 units
Open in Course

Problem - Random Pick with Weight

Weighted random selection

You have an array of positive integers representing weights. You need to pick an index randomly where the probability of picking index ii is proportional to its weight.

For example, if weights are [1,3,2][1, 3, 2], then index 00 has probability 16\frac{1}{6}, index 11 has probability 36=12\frac{3}{6} = \frac{1}{2}, and index 22 has probability 26=13\frac{2}{6} = \frac{1}{3}.

How can you implement this so each call runs fast, even if weights array is large?