filling a array with random numbers between 0-9 in c# [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:44:02

问题:

Possible Duplicate:
filling a array with uniqe random numbers between 0-9 in c#

I have a array like "page[100]" and i want to fill it with random numbers between 0-9 in c#... how i can do this? i used :

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);     } } 

this way :

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

but it just gave me 9 unique random numbers but i need more. how i can have a array with random numbers that are not all the same?

回答1:

How about

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


回答2:

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); 


回答3:

You have an array of 100 numbers and draw from a pool of 10 different ones. How would you expect there to be no duplicates?

Don't overcomplicate the thing, just write what needs to be written. I.e.:

  1. Create the array
  2. Loop over the size of it
  3. Put a random number between from [0, 9] in the array.


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!