从 List<T> 中选择 N 个随机元素在 C# 中 [英] Select N random elements from a List&lt;T&gt; in C#

查看:38
本文介绍了从 List<T> 中选择 N 个随机元素在 C# 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个快速算法来从通用列表中选择 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# 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆