Select random item with weight

前端 未结 5 1759
执笔经年
执笔经年 2020-12-15 00:48

I have a list of approx. 10000 items. The current situation is that every item has an associated weight (priority or importance). Now the smallest weight is -100

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-15 01:15

    It's easier to do if the weights are not negative. If you have to have negative weights, you'll have to offset the weights by the lowest possible weight. In your case, offsetted_weight = itemweight + 100

    In pseudocode, it goes like this:

    Calculate the sum of all the weights.
    Do a random from 0 to the sum of the weights
    Set i to 0
    While the random number > 0
        Subtract the weight of the item at index i  from random
        If the random number is < 0 return item[i]
        Add 1 to i
    

提交回复
热议问题