The key to developing lottery applications is to ensure random sorting of list elements. This article discusses the best way to achieve the generic list
random sorting in C#.
<list>
Fisher-Yates shuffle algorithm
Fisher-Yates shuffle algorithm is a method of efficient disruption of generic lists. The algorithm operates through the extension method Interface:
How to use: IList
private static Random rng = new Random(); public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = rng.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } }
<机> The consideration of the random number generator
IList
<虽然> Although the class is convenient, its randomness may be insufficient. In order to improve the randomness, it is recommended to use the random number generator in
List<Product> products = GetProducts(); products.Shuffle();
<程> Thread security improvement
In order to avoid potential problems in multi -threaded environments, it can improve thread security: System.Random
System.Security.Cryptography
using System.Security.Cryptography; ... public static void Shuffle<T>(this IList<T> list) { RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider(); int n = list.Count; while (n > 1) { byte[] box = new byte[1]; do provider.GetBytes(box); while (!(box[0] < 251)); // Ensure a valid range int k = (int)(box[0] / 251.0 * (n + 1)); // Scale to the list size T value = list[k]; list[k] = list[n]; list[n] = value; } }
Through these methods, you can effectively sort the elements in the generic list of generics to create a truly random lottery lottery application.
The above is the detailed content of How Can I Effectively Randomize a Generic List in C# for Lottery Applications?. For more information, please follow other related articles on the PHP Chinese website!