一個C#隨機數的問題,解決隨機數重復


默認情況下,.NET的隨機數是根據系統時間來生成的,如果電腦速度很快的話,生成的隨機數就會一樣。
Random rnd = new Random(); 
int rndNum = rnd.Next();         //int 取值范圍內的隨機數 
int rndNum = rnd.Next(10);       //得0~9的隨機數 
int rndNum = rnd.Next(10,20);    //得10~19的隨機數 
int rndNum = rnd.NextDouble();   //得0~1的隨機數  
若隨機種子為系統時間,用循環一次生成多個隨機數.
因為CPU運算速度太快了,所以每次取到的都是同一個時間.即生成的數字都一樣了.
所以要不停地變換種子.
        public string GetRandomCode()
         {
             char[] chars = {
                                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S',
                                'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'
                            };
             string code = string.Empty;
             for (int i = 0; i < 4; i++)
             {
                 //這里是關鍵,傳入一個seed參數即可保證生成的隨機數不同            
                 //Random rnd = new Random(unchecked((int)DateTime.Now.Ticks));
                 Random rnd = new Random(GetRandomSeed( ));
                 code += chars[rnd.Next(0, 30)].ToString();
             }
             return code;
         }
        /// <summary>
        /// 加密隨機數生成器 生成隨機種子
        /// </summary>
        /// <returns></returns>
    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);
    }
獲取指定數量的隨機組合 洗牌程序 思路
    public static IList<string> CreateChargeCodeNo(string PromotionChargeCodeNo, int Count)
    {
        List<string> lis = new List<string>();
        if (string.IsNullOrEmpty(PromotionChargeCodeNo))
        {
            return lis;
        }
        string ChargeCodeNo = PromotionChargeCodeNo;
        int length = 10 - PromotionChargeCodeNo.Length;
        while (lis.Count < Count)
        {
            int[] numbers = new int[length * 2];
            for (int i = 0; i < length * 2; i++)
                numbers[i] = i + 1;
            for (int i = 0; i < length * 2; i++)//二倍體洗牌
            {
                Random rand = new Random(GetRandomSeed());
                int temp = rand.Next(length * 2);
                int tempNumber = numbers[i];
                numbers[i] = numbers[temp];
                numbers[temp] = tempNumber;
            }
            string code = "";
            for (int x = 0; code.Length < length; x++)
            {
                code += numbers[x];
            }
            code = code.Substring(0, length);
            string s = ChargeCodeNo + code;
            if (lis.Contains(s))
            {
                continue;
            }
            lis.Add(ChargeCodeNo + code);
        }
        return lis;
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM