How do I find duplicates in an array and display how many times they occurred? How do I find duplicates in an array and display how many times they occurred? arrays arrays

How do I find duplicates in an array and display how many times they occurred?


Since you can't use LINQ, you can do this with collections and loops instead:

static void Main(string[] args){                  int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };    var dict = new Dictionary<int, int>();        foreach(var value in array)    {        // When the key is not found, "count" will be initialized to 0        dict.TryGetValue(value, out int count);        dict[value] = count + 1;    }        foreach(var pair in dict)        Console.WriteLine("Value {0} occurred {1} times.", pair.Key, pair.Value);    Console.ReadKey();}


Use Group by:

int[] values = new []{1,2,3,4,5,4,4,3};var groups = values.GroupBy(v => v);foreach(var group in groups)    Console.WriteLine("Value {0} has {1} items", group.Key, group.Count());


Let's take a look at a simpler example. Let's say we have the array {0, 0, 0, 0}.

What will your code do?

It will first look to see how many items after the first item are equal to it. There are three items after the first that are equal to it.

Then it goes to the next item, and looks for all items after it that are equal to it. There are two. So far we're at 5, and we haven't even finished yet (we have one more to add), but there are only four items in the whole array.

Clearly we have an issue here. We need to ensure that when we've searched the array for duplicates of a given item that we don't search through it again for that same item. While there are ways of doing that, this fundamental approach is looking to be quite a lot of work.

Of course, there are different approaches entirely that we can take. Rather that going through each item and searching for others like it, we can loop through the array once, and add to a count of number of times we've found that character. The use of a Dictionary makes this easy:

var dictionary = new Dictionary<int, int>();foreach (int n in array){    if (!dictionary.ContainsKey(n))        dictionary[n] = 0;    dictionary[n]++;}

Now we can just loop through the dictionary and see which values were found more than once:

foreach(var pair in dictionary)    if(pair.Value > 1)        Console.WriteLine(pair.Key);

This makes the code clear to read, obviously correct, and (as a bonus) quite a lot more efficient than your code, as you can avoid looping through the collection multiple times.