Randomly selecting an element from a weighted list

后端 未结 5 1248
臣服心动
臣服心动 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:23

    A solution that runs in O(n) would be to start out with selecting the first element. Then for each following element either keep the element you have or replace it with the next one. Let w be the sum of all weights for elements considered so far. Then keep the old one with probability w/(w+x) and choose the new one with p=x/(w+x), where x is the weight of the next element.

提交回复
热议问题