0

I would like to compare the elements of a array fed by random values to see if this value has not been added a second time in my array

static void Main(string[] args)
{
    Random rand = new Random();

    int[] elements = new int[8];
    int lo = rand.Next(1, 49);
    for (int i = 0; i < elements.Length; i++)
    {
        lo = rand.Next(1, 49);
        elements[i] = lo;
    }

    for (int i = 0; i < elements.Length; i++)
    {
        if (elements[i] == elements[elements.Length - 2])
        {

        }
    }

    for (int x = 0; x < elements.Length; x++)
    {
        Console.WriteLine(elements[x]);
    }
}
CSDev
  • 3,177
  • 6
  • 19
  • 37
AnTs
  • 3
  • 1

3 Answers3

1
var hasDuplicates = elements
    .GroupBy(entry => entry)
    .Select(group => new { Entry = group.Key, Count = group.Count() })
    .Where(group => group.Count > 1).Count() > 0;
Ben Bancroft
  • 95
  • 10
1

The other answers correctly solves your problem of detecting if there are any duplicate entries using GroupBy. However, if your intent is to replace those duplicate entries with new non-existing entry in the array, you can use the methods below -

        Random rand = new Random();

        int[] elements = new int[8];
        int lo;
        for (int i = 0; i < elements.Length; i++)
        {
            do
                lo = rand.Next(1, 49);
            while (elements.Contains(lo));
            elements[i] = lo;
            Console.WriteLine(elements[i]);
        }

This code will guarantee that elements array will always have unique values.

Note :- do...while loop keep generating random numbers unless it finds a unique number. So if your array size is bigger then the range of random numbers generated you'll get stuck in an infinite loop.

Gaurav Mathur
  • 804
  • 5
  • 14
  • thank you very much for your answer which is excellent and precise and which has met my expectations – AnTs Aug 01 '19 at 16:51
0

Using the power of linq you can use the GroupBy to find your duplicates.

Also, Enumerable.Range is a quick way of generating lists.

public static void Main()
{
    var rand = new Random();

    var elements = Enumerable.Range(0, 8).Select(_ => rand.Next(1, 49));

    var duplicates = elements.GroupBy(x => x).Where(x => x.Count() > 1).ToArray();

    if (duplicates.Any())
    {
        Console.WriteLine("duplicates found");  
    }
    else
    {
        Console.WriteLine("no duplicates"); 
    }
}

If you need to act on the duplicates you can iterate them and use .Key

Josh
  • 16,286
  • 25
  • 113
  • 158