I'm trying to generate 5 random numbers between 1-10 which do not have duplicate values. Therefore, I've created a recursive method which should check to see if the value created for whichever position in the array has been used already. If it has, then it will create a new random number and check again.
Here's my code:
static Random randomObject = new Random();
static void Main(string[] args)
{
long[] randomArr = new long[5];
for (int i = 0; i < randomArr.Length; i++ )
{
if (randomArr[i] == randomArr[0])
{
randomArr[i] = randomObject.Next(1, 11);
}
else
{
long check = randomObject.Next(1, 11);
randomArr[i] = CheckIfUnique(check, randomArr);
}
}
Console.WriteLine("\nPress the [enter] key to continue...");
Console.ReadLine();
}
static long CheckIfUnique(long a, long[] b)
{
for (int i = 0; i <= b.GetUpperBound(0); i++)
{
if (a == b[i])
{
a = randomObject.Next(1, 11);
CheckIfUnique(a, b);
}
}
return a;
}
But I'm still getting duplicate values. Does anyone know if there is an error in my logic, or if the compiler will crap out after so many recursive steps?