[英]Picking the most items from array 1, less items from array 2 etc
如何根据它们的“重要性”随机无限循环地遍历这些数组中的对象?
test = [
important = [
"lorem",
"ipsum"
],
kinda_important = [
"dolor",
"sit"
],
not_so_important = [
"amet",
"consectetur"
]
]
test.shuffle.each do |test|
sleep 5
puts test
end
应该输出即:
lorem
lorem
sit
ipsum
lorem
ipsum
ipsum
dolor
ipsum
sit
amet
lorem
ipsum
dolor
lorem
sit
...
最important
是输出最频繁的地方, kinda_important
较少,等等。
似乎您需要在此处为您的重要性级别分配一些概率。 也许像这样重新定义您的数据结构
test = {
(0..49) => [ # most important
"lorem",
"ipsum"
],
(50..79) => [ # semi important
"dolor",
"sit"
],
(80..99) => [ # least important
"amet",
"consectetur"
]
}
然后做这样的事情。
while true
rand = Kernel.rand(100)
test.each do |range, options|
if range.include?(rand)
puts options.sample
end
end
end
您必须将这些几率的机会编辑为所需的随机性。
PS:通过执行Kernel.rand(100) + 1
(将生成1到100之间的数字,而不是0到99),并使其范围向上移动一,您可以使其更具可读性: (1..50)
= 50%, (51..75)
= 25%, (51..75)
。
您没有正确的数据对象。 您可以使用:
test = { important: ["lorem", "ipsum"],
kinda_important: ["dolor", "sit"],
not_so_important: ["amet", "consectetur"] }
您将需要一些概率:
probs = { important: 0.5, kinda_important: 0.3, not_so_important: 0.2 }
现在,我们可以生成所需的随机变量(用于hash
和probs
中元素的任意数量):
def deal(hash, probs, nbr)
last = 0.0
choices = probs.each_with_object({}) do |(group, prob),choices|
choices[last + prob] = group
last += prob
end
nbr.times.map do
rn = rand
hash[choices.find { |cum,ch| rn <= cum }.last].sample
end
end
deal(test, probs, 15)
#=> ["amet", "amet", "consectetur", "dolor", "lorem", "dolor", "amet",
# "sit", "sit", "lorem", "lorem", "lorem", "lorem", "ipsum", "ipsum"]
这里:
choices
#{0.5=>:important, 0.8=>:kinda_important, 1.0=>:not_so_important}
让我们尝试一下:
n = 10_000
a = deal(test, probs, n)
a.uniq.map { |s| [s, a.count(s).to_f/n] }.sort_by(&:last).reverse.to_h
#=> {"ipsum" =>0.2541, "lorem"=>0.25,
# "dolor" =>0.1513, "sit" =>0.1457,
# "consectetur"=>0.1016, "amet" =>0.097
如何将代码放入while
循环中:
while true
test.shuffle.each do |test|
puts test
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.