从 List<T> 中选择 N 个随机元素在 C# 中

编程入门 行业动态 更新时间:2024-10-19 01:24:59
本文介绍了从 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# 中

本文发布于:2023-11-29 12:42:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646426.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   List   lt   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!