Algorithm to shuffle an Array randomly based on different weights

后端 未结 6 811
天涯浪人
天涯浪人 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条回答
  •  南方客
    南方客 (楼主)
    2021-01-19 14:30

    Based on the @amit suggestion:

    def self.random_suffle_with_weight(elements, &proc)
      consecutive_chain = []
      elements.each do |element|
        proc.call(element).times { consecutive_chain << element }
      end
    
      consecutive_chain.shuffle.uniq
    end
    

提交回复
热议问题