C#生成指定范围内的不重复随机数

C#生成指定范围内的不重复随机数

 1 // Number随机数个数
 2 // minNum随机数下限
 3 // maxNum随机数上限
 4 public int[] GetRandomArray(int Number,int minNum,int maxNum)
 5  {
 6   int j;
 7   int[] b=new int[Number];
 8   Random r=new Random();
 9   for(j=0;j<Number;j++)
10   {
11   int i=r.Next(minNum,maxNum+1);
12   int num=0;
13   for(int k=0;k<j;k++)
14   {
15    if(b[k]==i)
16    {
17    num=num+1;
18    }
19   }
20   if(num==0 )
21   {
22    b[j]=i;
23   }
24   else
25   {
26    j=j-1;
27   }
28   }
29   return b;
30  }

下面来介绍下其他网友的实现方法:

方法1:思想是用一个数组来保存索引号,先随机生成一个数组位置,然后把随机抽取到的位置的索引号取出来,并把最后一个索引号复制到当前的数组位置,然后使随机数的上限减一,具体如:先把这100个数放在一个数组内,每次随机取一个位置(第一次是1-100,第二次是1-99,...),将该位置的数用最后的数代替。

 1 int[] index = new int[15]; 
 2 for (int i = 0; i < 15; i++) 
 3 index = i; 
 4 Random r = new Random(); 
 5 //用来保存随机生成的不重复的10个数 
 6 int[] result = new int[10]; 
 7 int site = 15;//设置上限 
 8 int id; 
 9 for (int j = 0; j < 10; j++) 
10 { 
11 id = r.Next(1, site - 1); 
12 //在随机位置取出一个数,保存到结果数组 
13 result[j] = index[id]; 
14 //最后一个数复制到当前位置 
15 index[id] = index[site - 1]; 
16 //位置的上限减少一 
17 site--; 
18 }

方法2:利用Hashtable

 1 Hashtable hashtable = new Hashtable(); 
 2 Random rm = new Random(); 
 3 int RmNum = 10; 
 4 for (int i = 0; hashtable.Count < RmNum; i++) 
 5 { 
 6   int nValue = rm.Next(100); 
 7 if (!hashtable.ContainsValue(nValue) && nValue != 0) 
 8 { 
 9   hashtable.Add(nValue, nValue); 
10   Console.WriteLine(nValue.ToString()); 
11 } 
12 }

方法3:递归,用它来检测生成的随机数是否有重复,如果取出来的数字和已取得的数字有重复就重新随机获取。

 1 Random ra=new Random(unchecked((int)DateTime.Now.Ticks)); 
 2 int[] arrNum=new int[10]; 
 3 int tmp=0; 
 4 int minValue=1; 
 5 int maxValue=10; 
 6 for (int i=0;i<10;i++) 
 7 { 
 8 tmp=ra.Next(minValue,maxValue); //随机取数 
 9 arrNum=getNum(arrNum,tmp,minValue,maxValue,ra); //取出值赋到数组中 
10 } 
11 ......... 
12 ......... 
13 public int getNum(int[] arrNum,int tmp,int minValue,int maxValue,Random ra) 
14 { 
15 int n=0; 
16 while (n<=arrNum.Length-1) 
17 { 
18 if (arrNum[n]==tmp) //利用循环判断是否有重复 
19 { 
20 tmp=ra.Next(minValue,maxValue); //重新随机获取。 
21 getNum(arrNum,tmp,minValue,maxValue,ra);//递归:如果取出来的数字和已取得的数字有重复就重新随机获取。 
22 } 
23 n++; 
24 } 
25 return tmp; 
26 }

来源:http://www.jb51.net/article/66255.htm

原文地址:https://www.cnblogs.com/dotnetHui/p/8080678.html