'Array.Exists verses Array.Contains: Why unexpected results?
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);
}
Solution 1:[1]
Array.Exists(array, element => element != num) means if there is at least one element in the array that is not equal to num.
the correct condition is !Array.Exists(array, element => element == num) which means there is no element in the array that equals to num
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Behnam Izadi |
