小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

C#產(chǎn)生不重復的隨機數(shù)

 XXG學習園 2012-03-30

方法1:思想是用一個數(shù)組來保存索引號,先隨機生成一個數(shù)組位置,然后把這個位置的索引號取出來,并把最后一個索引號復制到當前的數(shù)組位置,然后使隨機數(shù)的上限減一,具體如:先把這100個數(shù)放在一個數(shù)組內(nèi),每次隨機取一個位置(第一次是1-100,第二次是1-99,...),將該位置的數(shù)用最后的數(shù)代替。

  int[] index = new int[15];
  for (int i = 0; i < 15; i++)
    index = i;
  Random r = new Random();
  //用來保存隨機生成的不重復的10個數(shù)
  int[] result = new int[10];
  int site = 15;//設置下限
  int id;
  for (int j = 0; j < 10; j++)
  {
    id = r.Next(1, site - 1);
    //在隨機位置取出一個數(shù),保存到結(jié)果數(shù)組
    result[j] = index[id];
    //最后一個數(shù)復制到當前位置
    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:遞歸,用它來檢測生成的隨機數(shù)是否有重復,如果取出來的數(shù)字和已取得的數(shù)字有重復就重新隨機獲取

 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); //隨機取數(shù)
    arrNum=getNum(arrNum,tmp,minValue,maxValue,ra); //取出值賦到數(shù)組中
  }
  .........
  .........
  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) //利用循環(huán)判斷是否有重復
      {
        tmp=ra.Next(minValue,maxValue); //重新隨機獲取。
        getNum(arrNum,tmp,minValue,maxValue,ra);//遞歸:如果取出來的數(shù)字和已取得的數(shù)字有重復就重新隨機獲取。
      }
    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];


    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多