根据百分比选择数组中的随机对象

时间:2014-04-05 18:24:36

标签: ruby-on-rails ruby arrays

假设我有一个方法,它接受一个对象数组,每个对象都有一个百分比属性,用于控制方法返回元素的频率

IE中。我希望能够将一个对象添加到数组E,其中百分比属性为0.20并且大约每五次方法调用返回一次。实现这种方法的最佳方法是什么?

PS。不只是有一个包含5个对象的数组,而是随机选择一个

1 个答案:

答案 0 :(得分:3)

也许是这样的?

class Sample

  def initialize(e)
    @E = e
    @sums = []
    @E.each_with_index { |x, i| @sums << (@sums.last || 0) + @E[i][:pct] }
  end

  def draw
    rand = Random.rand()

    for i in 0..(@sums.length-1)
      return @E[i][:el] if rand <= @sums[i]
    end
  end

end

实施例

ss = Sample.new(e = [{el: "hello", pct: 0.3}, {el: "world", pct: 0.3}, {el: "goodbye", pct: 0.4}]) 
# Draw "hello" with 30%, "world" with 30%, "goodbye" with 40% probability, respectively   
results = []
10_000.times { results << ss.draw }
e.map { |x| { x[:el] => results.count { |y| y == x[:el] }.to_f / results.length } }.reduce(:merge)
# observed percentages of 10,000 draws
# {"hello"=>0.2938, "world"=>0.3046, "goodbye"=>0.4016}