2

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);
}
x0n
  • 51,312
  • 7
  • 89
  • 111
Calvin
  • 55
  • 1
  • 3
  • 3
    You didn't invert the condition correctly. It should be `!Exists(element => element != num)`, or just check `element => element == num` and switch the if branches around. Also note that there are [better ways](https://stackoverflow.com/questions/108819/best-way-to-randomize-an-array-with-net) to shuffle arrays. – Sweeper May 02 '22 at 14:24
  • 1
    Did @Sweeper's answer fix your problem? If so, someone should submit an answer. – Woody1193 May 02 '22 at 14:30

1 Answers1

4

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

Behnam
  • 337
  • 1
  • 6