问题描述
我需要一种快速算法来从通用列表中选择5个随机元素.例如,我想从 List< string>
中获得5个随机元素.
I need a quick algorithm to select 5 random elements from a generic list. For example, I'd like to get 5 random elements from a List<string>
.
推荐答案
对每个元素进行迭代并使其选择的概率=(所需数量)/(剩余数量)
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.
此技术称为选择抽样,这是水库采样的特例.它的性能类似于对输入进行混洗,但是当然可以在不修改原始数据的情况下生成样本.
This technique is called selection sampling, a special case of Reservoir Sampling. It's similar in performance to shuffling the input, but of course allows the sample to be generated without modifying the original data.
这篇关于从列表< T>中选择N个随机元素.在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!