C#短時間內產生不大量重復的隨機數

http://www.cnblogs.com/djlzxzy/archive/2011/08/10/2134276.html

在C#編程中,經常會碰到產生隨機數的情況,並且是在短時間內產生一組隨機數。如果這組隨機數中有大量重復的,則達不到我們的要求。生成隨機數可以用偽隨機數發生器Random,受種子控制生成偽隨機數,默認以當前時間值為種子。如果程序運行的很快,就會導致在幾乎同一時刻運行多次,肯定會有重復的。比如我們要生成1到10之間的5個隨機數,則經常會產生 2 2 1 1 1這樣的情況,那麼如何得到非常隨機的不那麼重復的隨機數呢?比如 4 2 3 3 5這樣的。

 

        有人說用Thread.Sleep(5) ,但我不推薦,因為這樣會使系統減緩運行。

        我采取的方法是:用種子Guid.NewGuid().GetHashCode(),在短時間裡不會出現大量重復。

       以下代碼中,得到的是1到20之間的10個隨機數(不包括20)。數組a、b、c分別采用不同的方法產生隨機數,數組a和b均調用了方法randbit,不同的是數組a多傳了一個參數i改變隨機數的種子,數組b用的方法是我在編程中經常用到的,即通過調用一個方法來產生隨機數,非常方便。數組c采用的方法也可以,但在實際編程中很少用到。數組d類似於數組c,只是產生的是0,1之間的隨機數。

代碼如下:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace ConsoleApplication12  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            int[] a = new int[10];  
            int[] b = new int[10];  
            int[] c = new int[10];  
            float[] d = new float[10];  
            int i;  
            Random ra = new Random(Environment.TickCount);  
            for (i = 0; i < 10; i++)  
            {  
                a[i] = randbit(1, 20, i);  
                b[i] = randbit(1, 20);  
                c[i] = ra.Next(1, 20);  
                d[i] = Convert.ToSingle(ra.NextDouble());  
            }  
            for (i = 0; i < 10; i++)  
            {  
                Console.WriteLine("a[" + "{0}" + "] = {1}/r", i, a[i]);  
            }  
            Console.WriteLine("/r");  
            for (i = 0; i < 10; i++)  
            {  
                Console.WriteLine("b[" + "{0}" + "] = {1}/r", i, b[i]);  
            }  
            Console.WriteLine("/r");  
            for (i = 0; i < 10; i++)  
            {  
                Console.WriteLine("c[" + "{0}" + "] = {1}/r", i, c[i]);  
            }  
            Console.WriteLine("/r");  
            for (i = 0; i < 10; i++)  
            {  
                Console.WriteLine("d[" + "{0}" + "] = {1}/r", i, d[i]);  
            }  
            Console.ReadLine();  
        }  
        public static int randbit(int i, int j, int p)  
        {  
            int a;  
            Random ra = new Random(Guid.NewGuid().GetHashCode() + p);  
            a = ra.Next(i, j);  
            return a;  
        }  
  
        public static int randbit(int i, int j)  
        {  
            int a;  
            Random ra = new Random(Guid.NewGuid().GetHashCode());  
            a = ra.Next(i, j);  
            return a;  
        }  
  
    }  
}  

得到的結果為:

  1. a[0] = 8  
  2. a[1] = 13  
  3. a[2] = 13  
  4. a[3] = 17  
  5. a[4] = 5  
  6. a[5] = 1  
  7. a[6] = 15  
  8. a[7] = 14  
  9. a[8] = 16  
  10. a[9] = 3  
  11.   
  12. b[0] = 9  
  13. b[1] = 13  
  14. b[2] = 11  
  15. b[3] = 1  
  16. b[4] = 2  
  17. b[5] = 15  
  18. b[6] = 5  
  19. b[7] = 11  
  20. b[8] = 6  
  21. b[9] = 13  
  22.   
  23. c[0] = 9  
  24. c[1] = 16  
  25. c[2] = 6  
  26. c[3] = 1  
  27. c[4] = 1  
  28. c[5] = 14  
  29. c[6] = 14  
  30. c[7] = 12  
  31. c[8] = 17  
  32. c[9] = 18  
  33.   
  34. d[0] = 0.8177258  
  35. d[1] = 0.998677  
  36. d[2] = 0.6717096  
  37. d[3] = 0.3508099  
  38. d[4] = 0.944403  
  39. d[5] = 0.7056777  
  40. d[6] = 0.1024248  
  41. d[7] = 0.2304256  
  42. d[8] = 0.1107363  
  43. d[9] = 0.5068604  
以下是我參考的別人的代碼:

usingSystem;     
usingSystem.Collections.Generic;     
usingSystem.Text;     
    
namespacetester     
{     
   ///<summary>     
   ///產生不重復隨機數的應用     
   ///鄭少東 2008.08.24     
   ///摘要 C#隨機數的應用中 如果是需要在短時間內產生大量隨機數 推薦使用Guid.NewGuid().GetHashCode()作為種子      
   ///</summary>     
   classProgram     
    {     
       staticvoidMain(string[] args)     
        {     
            Console.WriteLine(String.Format("開始時間{0}", DateTime.Now.ToString("yyyy-MM-dd hh:ss fff")));     
            List<int>Numbers=Program.GetRandom(1,1000);     
           for(inti=0; i<Numbers.Count;i++)     
            {     
               //Console.WriteLine(Numbers[i]);     
            }     
            Console.WriteLine(String.Format("結束時間{0}", DateTime.Now.ToString("yyyy-MM-dd hh:ss fff")));     
            Console.ReadLine();     
        }     
    
       ///<summary>     
       ///返回一組唯一不重復的隨機數     
       ///</summary>     
       ///<param name="minValue">最小值</param>     
       ///<param name="maxValue">最大值</param>     
       ///<returns>返回一組唯一不重復的隨機數</returns>     
       publicstaticList<int>GetRandom(intminValue,intmaxValue)     
        {     
            List<int>Numbers=newList<int>();     
           //使用Guid.NewGuid().GetHashCode()作為種子,可以確保Random在極短時間產生的隨機數盡可能做到不重復     
            Random rand=newRandom(Guid.NewGuid().GetHashCode());     
           intitem;     
           for(inti=minValue; i<=maxValue; i++)     
            {     
                item=rand.Next(minValue, maxValue+1);     
               while(Numbers.IndexOf(item)!=-1)     
                {     
                    item=rand.Next(minValue, maxValue+1);     
                }     
                Numbers.Add(item);     
            }     
           returnNumbers;     
        }     
    }     
}     


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值