[c#] Finding duplicate integers in an array and display how many times they occurred

I'm working on a code that prints out duplicated integers from an array with the number of their occurrence. I'm not allowed to use LINQ, just a simple code. I think I'm so close but confused about how to get a correct output:

class Program
{
    static void Main(string[] args)
    {              
        int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
        int count = 1;
        for (int i = 0; i < array.Length; i++)
        {
            for (int j = i; j < array.Length - 1 ; j++)
            {

               if(array[j] == array[j+1])
                  count = count + 1;
            }
            Console.WriteLine("\t\n " + array[i] + "occurse" + count);
            Console.ReadKey();
        }
    }
}

This question is related to c# arrays duplicates

The answer is


int copt = 1;
int element = 0;
int[] array = { 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5 };
for (int i = 0; i < array.Length; i++)
{
   for (int j = i + 1; j < array.Length - 1; j++)
   {
       if (array[i] == array[j])
       {
          element = array[i];
          copt++;
          break;
       }
   }
}

Console.WriteLine("the repeat element is {0} and it's appears {1} times ", element, copt);
Console.ReadKey();

// the output is the element is 3 and appears 9 times


 class Program
{
    static void Main(string[] args)
    {
        int[] arr = new int[] { 10, 20,20, 30, 10, 50 ,50,9};
        List<int> listadd = new List<int>();

        for (int i=0; i <arr.Length;i++)
        {
           int count = 0;
            int flag = 0;

            for(int j=0; j < arr.Length; j++)
            {
                if (listadd.Contains(arr[i]) == false)
                {


                    if (arr[i] == arr[j])
                    {
                        count++;
                    }

                } 

                else
                {
                    flag = 1;
                }

            }
            listadd.Add(arr[i]);
            if(flag!=1)
            Console.WriteLine("No of occurance {0} \t{1}", arr[i], count);
        }
        Console.ReadLine();

    }
}

I'm in agreement that using Dictionary is better running time performance then nested for loops (O(n) vs O(n^2)). However to address OP, here is a solution where a HashSet is used to prevent repeating the counting of integers already counted, such as integer 5 in example array.

static void Main(string[] args)
{              
    int[] A = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };

    var set = new HashSet<int>();
    for (int i = 0; i < A.Length - 1; i++) {
        int count = 0;
        for (int j = i; j < A.Length - 1; j++) {
            if (A[i] == A[j + 1] && !set.Contains(A[i]))
                count++;
        }
        set.Add(A[i]);
        if (count > 0) {
            Console.WriteLine("{0} occurs {1} times", A[i], count + 1);
            Console.ReadKey();
        }
    }
}

Ok I have modified your code. This should do the job:

class Program
{
    static void Main(string[] args)
    {
        int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };

        for (int i = 0; i < array.Length; i++)
        {
            int count = 0;
            for (int j = 0; j < array.Length; j++)
            {

                if (array[i] == array[j])
                    count = count + 1;
            }
            Console.WriteLine("\t\n " + array[i] + " occurs " + count + " times");
        }
        Console.ReadKey();
    }
}

 class Program
{
    static void Main(string[] args)
    {
        int[] arr = { 2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12 };
        List<int> nums = new List<int>();
        List<int> count = new List<int>();
        nums.Add(arr[0]);
        count.Add(1);
        for (int i = 1; i < arr.Length; i++)
        {

            if(nums.Contains(arr[i]))
            {
                count[nums.IndexOf(arr[i])] += 1;
            }
            else
            {
                nums.Add(arr[i]);
                count.Add(1);
            }
        }

        for(int x =0; x<nums.Count;x++)
        {
            Console.WriteLine("number:"+nums[x] +"Count :"+ count[x]);
        }
        Console.Read();
    }
}

int[] arr = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
var result = arr.GroupBy(x => x).Select(x => new { key = x.Key, val = x.Count() });       
foreach (var item in result)
{
    if(item.val > 1)
    {                
        Console.WriteLine("Duplicate value : {0}", item.key);
        Console.WriteLine("MaxCount : {0}", item.val);
    }

}

Console.ReadLine();

Here is an answer that avoids using Dictionaries. Since the OP said he is not familiar with them, this might give him a little insight into what Dictionaries do.

The downside to this answer is you have to enforce a limit on the max number in the array, and you can't have negative numbers. You'd never actually use this version in real code.

int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int[] count = new int[13];

foreach(int number in array) {
    // using the index of count same way you'd use a key in a dictionary
    count[number]++;
}

foreach(int c in count) {
    int numberCount = count[c];
    if(numberCount > 0) {
        Console.WriteLine(c + " occurs " + numberCount + " times");
    }
}

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());

int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 7, 7, 8, 9, 7, 12, 12 };
Dictionary<int, int> duplicateNumbers = new Dictionary<int, int>();
int count=1;
for (int i = 0; i < array.Length; i++)
{
    count=1;
    if(!duplicateNumbers.ContainsKey(array[i]))
    {
        for (int j = i; j < array.Length-1; j++)
        {
            if (array[i] == array[j+1])
            {
                count++;                            
            }
        }
        if (count > 1)
        {
            duplicateNumbers.Add(array[i], count);
        }
    }
}
foreach (var num in duplicateNumbers)
{
    Console.WriteLine("Duplicate numbers, NUMBER-{0}, OCCURRENCE- {1}",num.Key,num.Value);
}

public class Program
{
    public static void Main(string[] args)
    {
        int[] arr = new int[]{10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12};

        int numberOfDuplicate = 0;
        int arrayLength = arr.Length;

        for(int i=0; i < arrayLength; i++)  
        {  
           for(int j = 1; j < arrayLength; j++)  
           {
               if(j < i && arr[j]==arr[i])
               {
                  break; 
               }
               else if(i != j && arr[i]==arr[j])
               {
                  Console.Write("duplicate : arr[{0}]={1}--arr[{2}]={3}\n",i,arr[i],j,arr[j]);
                  numberOfDuplicate++;
                  break;
               }
           }
        }

        Console.Write("Total duplicate element in an array 'arr' is {0}\n ",numberOfDuplicate);
    }
}

static void printRepeating(int []arr, int size) { int i;

    Console.Write("The repeating" +  
                   " elements are : "); 

    for (i = 0; i < size; i++) 
    { 
        if (arr[ Math.Abs(arr[i])] >= 0) 
            arr[ Math.Abs(arr[i])] = 
                -arr[ Math.Abs(arr[i])]; 
        else
            Console.Write(Math.Abs(arr[i]) + " "); 
    }          
}  

public static void Main(string[] args)

{

Int[] array = {10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12};

List<int> doneNumbers = new List<int>();


for (int i = 0; i < array.Length - 1; i++)

{

    if(!doneNumbers.Contains(array[i]))

    {

        int currentNumber = array[i];

        int count = 0;

        for (int j = i; j < array.Length; j++)

        {

            if(currentNumber == array[j])

            {

                count++;

            }

        }

        Console.WriteLine("\t\n " + currentNumber +" "+ " occurs " + " "+count + " "+" times");

        doneNumbers.Add(currentNumber);

        Console.ReadKey();
      }

   }

}

}

}


// This method counts a total number of duplicate elements in an array

public void DuplicateElementsInArray(int[] numbers)
    {
        int count = 0;

        for (int i = 0; i < numbers.Length; i++)
        {

            for (int j = i; j < numbers.Length - 1; j++)
            {
                if (numbers[i] == numbers[j+1])
                {                       
                    count++;
                    break;
                }                       
            }               
        }
        Console.WriteLine("Total number of duplicate elements found in the array is: {0}", count);
    }

You made a minor mistake of using J instead of i ...

class Program
{
    static void Main(string[] args)
    {              
        int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
        int count = 1;
        for (int i = 0; i < array.Length; i++)
        {
            for (int j = i; j < array.Length - 1 ; j++)
            {
               if(array[i] == array[j+1])
                  count = count + 1;
            }
            Console.WriteLine("\t\n " + array[i] + "occurse" + count);
            Console.ReadKey();
        }
    }
}

This approach, fixed up, will give the correct output (it's highly inefficient, but that's not a problem unless you're scaling up dramatically.)

int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
    int count = 0;
    for (int j = 0; j < array.Length ; j++)
    {
       if(array[i] == array[j])
          count = count + 1;
    }
    Console.WriteLine("\t\n " + array[i] + " occurs " + count);
    Console.ReadKey();
}

I counted 5 errors in the OP code, noted below.

int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int count = 1;                                   // 1. have to put "count" in the inner loop so it gets reset
                                                 // 2. have to start count at 0
for (int i = 0; i < array.Length; i++)
{
    for (int j = i; j < array.Length - 1 ; j++)  // 3. have to cover the entire loop
                                                 // for (int j=0 ; j<array.Length ; j++)
    {
       if(array[j] == array[j+1])                // 4. compare outer to inner loop values
                                                 // if (array[i] == array[j])
          count = count + 1;
    }
    Console.WriteLine("\t\n " + array[i] + "occurse" + count);
                                                 // 5. It's spelled "occurs" :)
    Console.ReadKey();
}

Edit

For a better approach, use a Dictionary to keep track of the counts. This allows you to loop through the array just once, and doesn't print duplicate counts to the console.

var counts = new Dictionary<int, int>();
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
    int currentVal = array[i];
    if (counts.ContainsKey(currentVal))
        counts[currentVal]++;
    else
        counts[currentVal] = 1;
}
foreach (var kvp in counts)
    Console.WriteLine("\t\n " + kvp.Key + " occurs " + kvp.Value);

You can check the following codes. The codes are working.

 class Program {
    static void Main(string[] args) {
      int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
      int count = 1;
      for (int i = 0; i < array.Length; i++) {
        for (int j = i + 1; j < array.Length; j++) {

          if (array[j] == array[j])
            count = count + 1;
        }
        Console.WriteLine("\t\n " + array[i] + " out of " + count);
        Console.ReadKey();
      }
    }
  }

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.


/This is the answer that helps you to find the duplicate integer values using Forloop and it will return only the repeated values apart from its times of occurences/

    public static void Main(string[] args)
    {
        //Array list to store all the duplicate values
        int[] ary = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
        ArrayList dup = new ArrayList();

        for (int i = 0; i < ary.Length; i++)
        {
            for (int j = i + 1; j < ary.Length; j++)
            {
                if (ary[i].Equals(ary[j]))
                {
                    if (!dup.Contains(ary[i]))
                    {
                        dup.Add(ary[i]);
                    }
                }
            }
        }
        Console.WriteLine("The numbers which duplicates are");
        DisplayArray(dup);
    }
    public static void DisplayArray(ArrayList ary)
    {
        //loop through all the elements
        for (int i = 0; i < ary.Count; i++)
        {
            Console.Write(ary[i] + " ");
        }
        Console.WriteLine();
        Console.ReadKey();
    }

using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    /// <summary>
    /// How do you find the duplicate number on a given integer array?
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };

            Dictionary<int, int> duplicates = FindDuplicate(array);

            Display(duplicates);

            Console.ReadLine();
        }

        private static Dictionary<T, int> FindDuplicate<T>(IEnumerable<T> source)
        {
            HashSet<T> set = new HashSet<T>();
            Dictionary<T, int> duplicates = new Dictionary<T, int>();

            foreach (var item in source)
            {
                if (!set.Add(item))
                {
                    if (duplicates.ContainsKey(item))
                    {
                        duplicates[item]++;
                    }
                    else
                    {
                        duplicates.Add(item, 2);
                    }
                }
            }

            return duplicates;
        }

        private static void Display(Dictionary<int, int> duplicates)
        {
            foreach (var item in duplicates)
            {
                Console.WriteLine($"{item.Key}:{item.Value}");
            }
        }
    }
}

Just use the code below,no need to use dictionary or ArrayList.Hope this helps :)

public static void Main(string[] args)
{              
    int [] array =new int[]{10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12};
    Array.Sort(array);
    for (int i = 0; i < array.Length; i++)
    {
        int count = 1,k=-1;
        for (int j = i+1; j < array.Length; j++)
        {  

                if(array[i] == array[j])
                {
                    count++;
                    k=j-1;
                }
                else break;
        }
        Console.WriteLine("\t\n " + array[i] + "---------->" + count);            
        if(k!=-1)
            i=k+1;          
    }
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to duplicates

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C Remove duplicates from a dataframe in PySpark How to "select distinct" across multiple data frame columns in pandas? How to find duplicate records in PostgreSQL Drop all duplicate rows across multiple columns in Python Pandas Left Join without duplicate rows from left table Finding duplicate integers in an array and display how many times they occurred How do I use SELECT GROUP BY in DataTable.Select(Expression)? How to delete duplicate rows in SQL Server? Python copy files to a new directory and rename if file name already exists