简体   繁体   English

如何从集合中随机获取字符串,但更喜欢集合开头的字符串

[英]How to randomly get a string from a collection but prefer strings at the beginning of the collection

If I have a list that contains the following strings: 如果我有一个包含以下字符串的列表:

  "a","b","c","d","e","f","g","h","i","j","k","l","m","n"

What is the best way to get a random string but be weighted in a way that it will be more likely to get "a" rather than "n"? 获取随机字符串的最佳方法是什么,但加权的方式更可能是“a”而不是“n”?

Select two random numbers and pick the lower one. 选择两个随机数并选择较低的一个。

Random rnd = new Random();
var randomItem = list[Math.Min(rnd.Next(list.Count+1), rnd.Next(list.Count+1))];

And I'd urge you to determine for yourself the resulting relative probabilities of each item. 我建议你自己确定每个项目的相对概率。

If you come up with a more rigorous definition of 'best' then this answer probably won't suit it. 如果你想出一个更严格的'最佳'定义,那么这个答案可能不适合它。

What is the best way to get a random string but be weighted in a way that it will be more likely to get "a" rather than "n"? 获取随机字符串的最佳方法是什么,但加权的方式更可能是“a”而不是“n”?

You should clarify the distribution you are willing to get. 您应该澄清您愿意获得的分配。 "More likely" is not clear enough. “更有可能”还不够明确。

By example, you might use: 例如,您可以使用:

for i in 1..size(array) do
  if random(0.0,1.0) < k then
    return array[i]
end for
return array[i]

But for different values of k , you'll get much different behavior. 但是对于不同的k值,你会得到很多不同的行为。

For k=1.0 , you'll always get the first element. 对于k=1.0 ,您将始终获得第一个元素。 For k=1/size(array) , you'll get a random element. 对于k=1/size(array) ,您将获得一个随机元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM