-7

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?

Community
  • 1
  • 1
Nimait70
  • 25
  • 2
  • 3
  • 5

3 Answers3

3

How about

int[] page = new int[100];
Random rnd = new Random();
for (int i = 0; i < page.Length; ++i)
  page[i] = rnd.Next(10);
Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
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);
juergen d
  • 201,996
  • 37
  • 293
  • 362
0

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.
Joey
  • 344,408
  • 85
  • 689
  • 683