Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equal values in array [duplicate]

Tags:

arrays

c#

How can I check if there are two or more equal values in one array?

eg. in this example, i want the program to tell me that there is a pair of 2 and a pair of 4

int[] array1 = { 1, 2, 4, 2, 4 };
like image 286
Mancato Il Dottore Avatar asked Dec 08 '22 15:12

Mancato Il Dottore


2 Answers

Using Linq

var result = array1.GroupBy(i=>i)
                .Select(g=>new {Value = g.Key, Count = g.Count()})
                .Where(x=>x.Count>1)
                .ToList();

foreach (var pair in result)
{
     Console.WriteLine("PAIR: " + pair.Value + " COUNT: " + pair.Count);
}
like image 140
I4V Avatar answered Dec 11 '22 09:12

I4V


[EDIT] Sorry, this answers the question "How can I check if there are two or more equal values in one array?", but it doesn't tell you the actual duplicates...


This would work, but possibly it isn't the most efficient way!

int[] array1 = { 1, 2, 4, 2, 4 };

if (array1.Distinct().Count() < array1.Length)
    Console.WriteLine("Contains Dupes");

If you want the most efficient approach:

bool containsDupes(int[] array)
{
    for (int i = 0; i < array.Length - 1; ++i)
    {
        int n = array[i];

        for (int j = i+1; j < array.Length; ++j)
            if (array[j] == n)
                return true;
    }

    return false;
}

I don't think you can get much more efficient than that. It will return as soon as it finds any match.

like image 31
Matthew Watson Avatar answered Dec 11 '22 07:12

Matthew Watson