随机化列表
在 C# 中随机化通用列表顺序的最佳方法是什么? 我在一个列表中有一组有限的 75 个数字,我想为其分配随机顺序,以便为彩票类型应用程序抽取它们。
What is the best way to randomize the order of a generic list in C#? I've got a finite set of 75 numbers in a list I would like to assign a random order to, in order to draw them for a lottery type application.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
我对这个简单算法的所有笨拙版本感到有点惊讶。 Fisher-Yates(或 Knuth shuffle)有点棘手,但非常紧凑。 为什么它很棘手? 因为您需要注意随机数生成器
r(a,b)
返回的值是包含还是不包含b
。 我还编辑了维基百科描述,这样人们就不会盲目地遵循伪代码并产生难以检测的错误。 对于 .Net,Random.Next(a,b)
返回不包括b
的数字,所以言归正传,以下是它在 C#/.Net 中的实现方式:尝试此代码。
I'm bit surprised by all the clunky versions of this simple algorithm here. Fisher-Yates (or Knuth shuffle) is bit tricky but very compact. Why is it tricky? Because your need to pay attention to whether your random number generator
r(a,b)
returns value whereb
is inclusive or exclusive. I've also edited Wikipedia description so people don't blindly follow pseudocode there and create hard to detect bugs. For .Net,Random.Next(a,b)
returns number exclusive ofb
so without further ado, here's how it can be implemented in C#/.Net:Try this code.
IEnumerable的扩展方法:
Extension method for IEnumerable:
想法是获取具有项目和随机顺序的匿名对象,然后按此顺序重新排序项目并返回值:
Idea is get anonymous object with item and random order and then reorder items by this order and return value:
从 .NET 8 开始,您可以使用
Shuffle()
:或者,对于加密的强随机性:
对于列表,您必须首先创建一个数组 (
myList.ToArray()
),如上所示进行随机播放然后从打乱后的数组中创建一个新列表Starting in .NET 8, you can use
Shuffle()
:Or, for a cryptographically strong randomness:
For a list, you would have to create an array first (
myList.ToArray()
) shuffle as above and then create a new list from the shuffled array编辑
RemoveAt
是我之前版本中的一个弱点。 这个解决方案克服了这个问题。请注意可选的
随机生成器
,如果Random
的基本框架实现不是线程安全的或加密强度不足以满足您的需求,您可以将您的实现注入到操作中。可以在此答案中找到线程安全加密强
Random
实现的合适实现。这是一个想法,以(希望)有效的方式扩展 IList。EDIT
The
RemoveAt
is a weakness in my previous version. This solution overcomes that.Note the optional
Random generator
, if the base framework implementation ofRandom
is not thread-safe or cryptographically strong enough for your needs, you can inject your implementation into the operation.A suitable implementation for a thread-safe cryptographically strong
Random
implementation can be found in this answer.Here's an idea, extend IList in a (hopefully) efficient way.可以使用 morelinq 包中的 Shuffle 扩展方法,它适用于 IEnumerables
One can use the Shuffle extension methond from morelinq package, it works on IEnumerables
当希望不修改原始内容时,这是我首选的随机播放方法。 它是 Fisher–Yates "inside- 的变体- out”算法适用于任何可枚举序列(
source
的长度不需要从一开始就知道)。该算法还可以通过分配从
0
到length - 1
的范围并通过将随机选择的索引与最后一个索引交换来随机耗尽索引直到所有索引都已完成来实现。仅选择一次。 上面的代码完成了完全相同的事情,但没有额外的分配。 这非常整洁。对于
Random
类,它是一个通用数字生成器(如果我正在运行彩票,我会考虑使用不同的东西)。 默认情况下,它还依赖于基于时间的种子值。 问题的一个小缓解是使用RNGCryptoServiceProvider
为Random
类提供种子,或者您可以在与此类似的方法中使用RNGCryptoServiceProvider
(请参阅生成统一选择的随机双浮点值,但运行彩票几乎需要了解随机性和随机源的性质。生成随机双精度数(仅在 0 和 1 之间)的目的是用于缩放到整数解。 如果您需要从基于随机双
x
的列表中选择某些内容,则始终为0 <= x && x < 1
很简单。享受!
This is my preferred method of a shuffle when it's desirable to not modify the original. It's a variant of the Fisher–Yates "inside-out" algorithm that works on any enumerable sequence (the length of
source
does not need to be known from start).This algorithm can also be implemented by allocating a range from
0
tolength - 1
and randomly exhausting the indices by swapping the randomly chosen index with the last index until all indices have been chosen exactly once. This above code accomplishes the exact same thing but without the additional allocation. Which is pretty neat.With regards to the
Random
class it's a general purpose number generator (and If I was running a lottery I'd consider using something different). It also relies on a time based seed value by default. A small alleviation of the problem is to seed theRandom
class with theRNGCryptoServiceProvider
or you could use theRNGCryptoServiceProvider
in a method similar to this (see below) to generate uniformly chosen random double floating point values but running a lottery pretty much requires understanding randomness and the nature of the randomness source.The point of generating a random double (between 0 and 1 exclusively) is to use to scale to an integer solution. If you need to pick something from a list based on a random double
x
that's always going to be0 <= x && x < 1
is straight forward.Enjoy!
如果您不介意使用两个列表,那么这可能是最简单的方法,但可能不是最有效或不可预测的方法:
If you don't mind using two
Lists
, then this is probably the easiest way to do it, but probably not the most efficient or unpredictable one:只是想建议使用
IComparer
和List.Sort()
的变体:用法:
Just wanted to suggest a variant using an
IComparer<T>
andList.Sort()
:Usage:
您可以使用这个简单的扩展方法来实现这一点
,并且可以通过执行以下操作来使用它
You can achieve that be using this simple extension method
and you can use it by doing the following
我们可以使用 List 的扩展方法并使用线程安全的随机生成器组合。 我在 NuGet 上打包了此版本的改进版本,源代码可在 NuGet ="https://github.com/MarkCiliaVincenti/ListShuffle" rel="nofollow noreferrer">GitHub。 NuGet 版本包含可选的加密强随机数。
.NET 6.0 之前的版本:
在 .NET 6.0 或更高版本上:
通过 NuGet 安装库更多功能。
We can use an extension method for List and use a thread-safe random generator combination. I've packaged an improved version of this on NuGet with the source code available on GitHub. The NuGet version contains optional cryptographically-strong random.
Pre-.NET 6.0 version:
On .NET 6.0 or later:
Install the library via NuGet for more features.
如果您有固定数量 (75),则可以创建一个包含 75 个元素的数组,然后枚举列表,将元素移动到数组中的随机位置。 您可以使用 Fisher-Yates 生成列表编号到数组索引的映射随机播放。
If you have a fixed number (75), you could create an array with 75 elements, then enumerate your list, moving the elements to randomized positions in the array. You can generate the mapping of list number to array index using the Fisher-Yates shuffle.
我通常使用:
I usually use:
通过使用元组进行交换,您可以使 Fisher-Yates 洗牌变得更加简洁和富有表现力。
You can make the Fisher-Yates shuffle more terse and expressive by using tuples for the swap.
实现:
示例:
.NET Fiddle 中的演示
Implementation:
Example:
Demonstration in .NET Fiddle
对接受的答案进行简单修改,返回一个新列表而不是就地工作,并接受更通用的
IEnumerable
与许多其他 Linq 方法一样。A simple modification of the accepted answer that returns a new list instead of working in-place, and accepts the more general
IEnumerable<T>
as many other Linq methods do.这是 Fisher-Yates shuffle 的一个实现,它允许指定要返回的元素数量; 因此,在获取所需数量的元素之前,无需先对整个集合进行排序。
交换元素的顺序与默认顺序相反; 并从第一个元素继续到最后一个元素,以便检索集合的子集会产生与打乱整个集合相同的(部分)序列:
该算法基于 Durstenfeld 的(现代)版本的 Fisher-Yates shuffle。
Here is an implementation of the Fisher-Yates shuffle that allows specification of the number of elements to return; hence, it is not necessary to first sort the whole collection before taking your desired number of elements.
The sequence of swapping elements is reversed from default; and proceeds from the first element to the last element, so that retrieving a subset of the collection yields the same (partial) sequence as shuffling the whole collection:
This algorithm is based on Durstenfeld's (modern) version of the Fisher-Yates shuffle on Wikipedia.
这是一个高效的 Shuffler,它返回打乱值的字节数组。 它不会洗牌超过需要的数量。 它可以从之前停止的地方重新启动。 我的实际实现(未显示)是一个 MEF 组件,允许用户指定替换洗牌器。
`
Here's an efficient Shuffler that returns a byte array of shuffled values. It never shuffles more than is needed. It can be restarted from where it previously left off. My actual implementation (not shown) is a MEF component that allows a user specified replacement shuffler.
`
我在网上找到了一个有趣的解决方案。
礼貌:https://improveandrepeat .com/2018/08/a-simple-way-to-shuffle-your-lists-in-c/
var shuffled = myList.OrderBy(x => Guid.NewGuid()).ToList() ;
I have found an interesting solution online.
Courtesy: https://improveandrepeat.com/2018/08/a-simple-way-to-shuffle-your-lists-in-c/
var shuffled = myList.OrderBy(x => Guid.NewGuid()).ToList();
您的问题是如何随机化列表。 这意味着:
针对这个问题发布的大量答案不满足上述“随机”的两个要求。
这是遵循 Fisher-Yates 洗牌方法的紧凑、无偏伪随机函数。
Your question is how to randomize a list. This means:
A large number of the answers posted for this question do NOT satisfy the two requirements above for being "random".
Here's a compact, non-biased pseudo-random function following the Fisher-Yates shuffle method.
从
.net 8.0
(2023 年 11 月)开始,新的Random.Shuffle
和RandomNumberGenerator.Shuffle(Span)
方法让您随机化一系列项目的顺序。Beginning with
.net 8.0
(nov. 2023) The newRandom.Shuffle
andRandomNumberGenerator.Shuffle<T>(Span<T>)
methods let you randomize the order of a span of items.使用 C#12,建议的 Fisher-Yates shuffle 可以变得更加简洁,无需临时变量:
另请注意,根据约定,Enumerable 扩展应返回一个新集合,而不是就地修改源集合。
With C#12, the proposed Fisher-Yates shuffle can be made a bit more concise, removing the need for a temporary variable:
Also note that per convention, Enumerable extensions should return a new collection instead of modifying the source collection in-place.
这是执行此操作的线程安全方法:
Here's a thread-safe way to do this:
用法 :
usage :
使用基于 Fisher-Yates 的扩展方法随机播放任何
(I)List
shuffle:用法:
上面的代码使用备受批评的System.Random方法来选择交换候选者。 它很快,但没有应有的随机性。 如果您需要在随机播放中获得更好的随机性,请使用 System.Security.Cryptography 中的随机数生成器,如下所示:
可以进行简单的比较 在此博客(WayBack Machine)。
编辑:自从几年前写下这个答案以来,很多人都评论或写信给我,指出我的比较中存在的巨大愚蠢缺陷。 他们当然是对的。 如果按预期方式使用 System.Random,则没有任何问题。 在上面的第一个示例中,我在 Shuffle 方法内部实例化了 rng 变量,如果要重复调用该方法,这会带来麻烦。 下面是一个固定的完整示例,基于今天从 @weston 收到的非常有用的评论。
程序.cs:
Shuffle any
(I)List
with an extension method based on the Fisher-Yates shuffle:Usage:
The code above uses the much criticised System.Random method to select swap candidates. It's fast but not as random as it should be. If you need a better quality of randomness in your shuffles use the random number generator in System.Security.Cryptography like so:
A simple comparison is available at this blog (WayBack Machine).
Edit: Since writing this answer a couple years back, many people have commented or written to me, to point out the big silly flaw in my comparison. They are of course right. There's nothing wrong with System.Random if it's used in the way it was intended. In my first example above, I instantiate the rng variable inside of the Shuffle method, which is asking for trouble if the method is going to be called repeatedly. Below is a fixed, full example based on a really useful comment received today from @weston here on SO.
Program.cs:
如果我们只需要以完全随机的顺序打乱项目(只是为了混合列表中的项目),我更喜欢这个简单而有效的代码,通过 guid 对项目进行排序...
正如人们在评论中指出的那样,GUID 不是保证是随机的,所以我们应该使用真正的随机数生成器:
If we only need to shuffle items in a completely random order (just to mix the items in a list), I prefer this simple yet effective code that orders items by guid...
As people have pointed out in the comments, GUIDs are not guaranteed to be random, so we should be using a real random number generator instead: