2012-05-22 15 views
-6

可能重複:
filling a array with uniqe random numbers between 0-9 in c#填充0-9之間的隨機數一個陣列中的C#

我有一個像陣列 「頁[100]」,我想填寫隨機數在0-9之間的c#... 我怎麼能做到這一點? 我用:

IEnumerable<int> UniqueRandom(int minInclusive, int maxInclusive) 
{ 
    List<int> candidates = new List<int>(); 
    for (int i = minInclusive; i <= maxInclusive; i++) 
    { 
     candidates.Add(i); 
    } 
    Random rnd = new Random(); 
    while (candidates.Count > 1) 
    { 
     int index = rnd.Next(candidates.Count); 
     yield return candidates[index]; 
     candidates.RemoveAt(index); 
    } 
} 

這樣:

int[] page = UniqueRandom(0,9).Take(array size).ToArray(); 

,但它只是給了我9個唯一的隨機數字,但我需要更多。 我怎麼可以有一個隨機數不完全相同的數組?

+0

該代碼過於複雜。回顧最初的要求。 – 2012-05-22 06:35:00

+6

0到9之間不能有100個唯一的整數 – climbage

+0

這是他的,並且有答案...... – Nashibukasan

回答

1
Random r = new Random(); //add some seed 
int[] randNums = new int[100]; //100 is just an example 
for (int i = 0; i < randNums.Length; i++) 
    randNums[i] = r.Next(10); 
+0

這不會從[0,9]中繪製數字。 – Joey

+0

@Joey:你說得對。我錯過了。謝謝。 –

3

如何

int[] page = new int[100]; 
Random rnd = new Random(); 
for (int i = 0; i < page.Length; ++i) 
    page[i] = rnd.Next(10); 
0

你有100個數字數組,並從10成不同的人一個池中提取。你會如何期待沒有重複?

不要過度複雜的事情,只需寫出需要寫的東西。即:

  1. 超過它
  2. 陣列[9 0,]在從放之間的隨機數的大小創建陣列
  3. 環路。
+0

正是我想要做的......但如何? 我嘗試了很多方法,但我只給了相同的整數... – Nimait70