从列表中选择℃的随机N个元素; T>在C#元素、列表中、GT

2023-09-10 22:32:20 作者:他是我不能拥抱的太阳

我需要一个快速的算法来选择从一个普通的列表中随机5个元素。例如,我想从一个列表随机5元。

I need a quick algorithm to select a random 5 elements from a generic list. For example, I'd like to get a random 5 elements from a List.

推荐答案

遍历,并为每个元件进行选择的概率=(所需数)/(数左)

Iterate through and for each element make the probability of selection = (number needed)/(number left)

所以,如果你有40个项目,第一次将有5/40的几率被选中的。如果是,下一个具有4/39机会,否则它有一个5/39机会。到时候你到了最后,你将有你的5个项目,而且往往你会在此之前,有他们。

So if you had 40 items, the first would have a 5/40 chance of being selected. If it is, the next has a 4/39 chance, otherwise it has a 5/39 chance. By the time you get to the end you will have your 5 items, and often you'll have all of them before that.