基于RNGCryptoServiceProvider的洗牌算法
将1到100这个100个自然数, 随机放入一个长度为100的int数组中, 并且不能重复:
class Program { static void Main(string[] args) { int[] num = new int[100]; int index01; int index02; int tmp; for (int i=0; i<100; i++) { num[i] = i+1; } for(int i=0; i<100; i++) { index01 = GenerateRandom()%100; do { index02 = GenerateRandom() % 100; } while (index01 == index02); tmp = num[index01]; num[index01] = num[index02]; num[index02] = tmp; } for (int i = 0; i < 100; i++) { Console.WriteLine(num[i]); } Console.ReadKey(); } private static int GenerateRandom() { int seed = GetRandomSeed(); return new Random(seed).Next(); } /// <summary> /// 生成随机种子 /// </summary> /// <returns></returns> private static int GetRandomSeed() { byte[] bytes = new byte[4]; System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); rng.GetBytes(bytes); return BitConverter.ToInt32(bytes, 0); } }