gpt4 book ai didi

ruby-on-rails - 根据百分比选择数组中的随机对象

转载 作者:数据小太阳 更新时间:2023-10-29 08:47:38 24 4
gpt4 key购买 nike

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

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

附言。不仅仅是有 5 个对象的数组并随机选择一个

最佳答案

也许是这样的?

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}

关于ruby-on-rails - 根据百分比选择数组中的随机对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22884928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com