简体   繁体   中英

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"?

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"?

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.

For k=1.0 , you'll always get the first element. For k=1/size(array) , you'll get a random element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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