Algorithm to shuffle an Array randomly based on different weights

后端 未结 6 816
天涯浪人
天涯浪人 2021-01-19 14:19

I have a collection of elements that I want to shuffle randomly, but every element has a different priority or weight. So the element with bigger weight has to have more pro

6条回答
  •  Happy的楠姐
    2021-01-19 14:51

    Weighted Random Sampling (2005; Efraimidis, Spirakis) provides a very elegant algorithm for this. The implementation is super simple and runs in O(n log(n)):

    def weigthed_shuffle(items, weights):
        order = sorted(range(len(items)), key=lambda i: -random.random() ** (1.0 / weights[i]))
        return [items[i] for i in order]
    

提交回复
热议问题