C#产生不重复的随机数

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

  int[] index = new int[15];   for (int i = 0; i < 15; i++)     index = i;   Random r = new Random();   //用来保存随机生成的不重复的10个数   int[] result = new int[10];   int site = 15;//设置下限   int id;   for (int j = 0; j < 10; j++)   {     id = r.Next(1, site - 1);     //在随机位置取出一个数,保存到结果数组     result[j] = index[id];     //最后一个数复制到当前位置     index[id] = index[site - 1];     //位置的下限减少一     site--;   }

方法2:利用Hashtable。

  Hashtable hashtable = new Hashtable();   Random rm = new Random();   int RmNum = 10;   for (int i = 0; hashtable.Count < RmNum; i++)   {    int nValue = rm.Next(100);    if (!hashtable.ContainsValue(nValue) && nValue != 0)    {    hashtable.Add(nValue, nValue);    Console.WriteLine(nValue.ToString());    }   }

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

 Random ra=new Random(unchecked((int)DateTime.Now.Ticks));   int[] arrNum=new int[10];   int tmp=0;   int minValue=1;   int maxValue=10;   for (int i=0;i<10;i++)   {     tmp=ra.Next(minValue,maxValue); //随机取数     arrNum=getNum(arrNum,tmp,minValue,maxValue,ra); //取出值赋到数组中   }   .........   .........   public int getNum(int[] arrNum,int tmp,int minValue,int maxValue,Random ra)   {     int n=0;     while (n<=arrNum.Length-1)     {       if (arrNum[n]==tmp) //利用循环判断是否有重复       {         tmp=ra.Next(minValue,maxValue); //重新随机获取。         getNum(arrNum,tmp,minValue,maxValue,ra);//递归:如果取出来的数字和已取得的数字有重复就重新随机获取。       }     n++;     }     return tmp;   }

方法4 利用ArrayList

int[] intArr=new int[100];ArrayList myList=new ArrayList();Random rnd=new Random();while(myList.Count<100){int num=rnd.Next(1,101);if(!myList.Contains(num))myList.Add(num);}for(int i=0;i<100;i++)intArr[i]=(int)myList[i];

原文地址:https://www.cnblogs.com/xiexingen/p/2846536.html