フィッシャー - シャッフル拡張方法
の要素をランダムに破壊します。次のコードブロックは、Fisher-Yatesアルゴリズムを実装するための拡張方法を示しています:
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; } }
List<Product> products = GetProducts();
products.Shuffle();
以上がC#の一般的なリストを効率的かつ安全にランダムにシャッフルするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。using System.Security.Cryptography;
...
public static void Shuffle<T>(this IList<T> list)
{
using (RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider())
{
int n = list.Count;
while (n > 1)
{
byte[] box = new byte[1];
do provider.GetBytes(box);
while (!(box[0] < (byte)((double)uint.MaxValue / uint.MaxValue * n)));
int k = (int)(box[0] % n);
T value = list[k];
list[k] = list[n - 1];
list[n - 1] = value;
}
}
}