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

问题描述

我需要一个快速的算法来选择一个通用的清单5随机元素。例如,我想从得到5个随机元素的列表与LT;字符串方式>

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.

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

08-14 12:38