[Solved] Adding Random and Non-Recurring Numbers to an Array [closed]


You can generate random numbers by using the built in Random class, and use the array function Contains to check if the number generated is already in the array. In my example below I generate a new numbers until I find one that isn’t in the array yet, then add it.

Random rand = new Random();
int[] intArray = new int[100];
for (int i = 0; i < 100; i++)
{
    int next = 0;
    while (intArray.Contains(next = rand.Next())) { }
    intArray[i] = next;
}

Note: One drawback to this approach is that it is potentially non-terminating because it could infinitely produce the same numbers over and over that are already in the array. However, for most applications of this sort of thing I doubt it would be an issue.

0

solved Adding Random and Non-Recurring Numbers to an Array [closed]