问题描述
我需要一个快速算法来从通用列表中选择 5 个随机元素.例如,我想从 List
中获取 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>
.
推荐答案
迭代每个元素,使选择概率 = (number required)/(number left)
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.
这篇关于从 List<T> 中选择 N 个随机元素在 C# 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!