mercredi 19 avril 2017

Check for duplicates in c#

I would like to check the array I passed in the shuffle method for any duplicates. I would like to also generate a random number that is the size of a.length.

The thing is that I can't figure out how to check if the array has duplicates and if it does it would generate another number until it is unique from the rest.

public int[] Shuffle(int[] a)
    {

        //check if the array has duplicates
        for (int i = 0; i < a.Length; i++)
        {
            int curValue = random.Next(a.Length);
            if(a.Contains(curValue))
            {
                curValue = random.Next(a.Length);
            }
            else
            {
                a[i] = curValue;
            }
        }

        for (int i = 0; i < a.Length; i++)
        {
            int r = random.Next(a.Length);
            int t = a[r];
            a[r] = a[i];
            a[i] = t;
        }

        return a;
    }

Can anyone help me?




Aucun commentaire:

Enregistrer un commentaire