Randomly selecting an element from a weighted list

后端 未结 5 1254
臣服心动
臣服心动 2020-12-24 15:01

I have a list of 100,000 objects. Every list element has a \"weight\" associated with it that is a positive int from 1 to N.

What is the most efficient way to select

5条回答
  •  渐次进展
    2020-12-24 15:31

    If you know the sum of weights (in your case, 9) AND you use a random-access data structure (list implies O(n) access time), then it can be done fast:

    1) select a random element (O(1)). Since there is 1/num_elems chance for an element to be selected at this step, it allows us to use the num_elems* boost for step 2), thus accelerating the algorithm.

    2) compute its expected probability: num_elems * (weight/total_weight)

    3) take a random number in range 0..1, and if it's lesser than expected probability, you have the output. If not, repeat from step 1)

提交回复
热议问题