从列表中选择℃的随机N个元素; T>在C# [英] Select a random N elements from List<T> in C#

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

问题描述

我需要一个快速的算法来选择从一个普通的列表中随机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.

这篇关于从列表中选择℃的随机N个元素; T>在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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