In Visual Studio using C#, I have created a random number in Main so there is only one seed for the method ShuffleMyNumbersArray
which attempts to fill the array with unique numbers from 1 to 52. When I use Array.Contains
the results are repeatedly correct. However when I use Array.Exists
there are number duplications in the array with no apparent pattern. My question is why is this happening? What is it about Array.Exists
that I do not understand? The only thing I can think of is that it may have something to do with the "Not" comparison != num
.See the following code for comparison.
Code that works consistently:
public static void ShuffleMyNumbersArray(int[] array, Random rand)
{
int num = rand.Next(1, 53);
int i = 0;
do
{
if (array.Contains(num))
{
num = rand.Next(1, 53);
}
else
{
array[i] = num;
i++;
num = rand.Next(1, 53);
}
} while (i < 52);
}
Code that produces duplicate numbers in the array:
public static void ShuffleMyNumbersArray(int[] array, Random rand)
{
int num = rand.Next(1, 53);
int i = 0;
do
{
if (Array.Exists(array, element => element != num))
{
array[i] = num;
i++;
num = rand.Next(1, 53);
}
else
{
num = rand.Next(1, 53);
}
} while (i < 52);
}