1. 程式人生 > >基於RNGCryptoServiceProvider的洗牌算法

基於RNGCryptoServiceProvider的洗牌算法

sta tel graph blog ring 生成 i++ index read

將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); } }

基於RNGCryptoServiceProvider的洗牌算法