Find duplicate array elements & count its occurence in c#


Hi, I have to find the repetition of number of occurence of an element in an array in c#, here is my current code for simple array

static void Main(string[] args)
{

     int[] t = new int[]{ 1,1,4, 9, 2,2 };
     for (int i = 0; i < t.Length; i++)
    {
        if (t[i] == t[i + 1])
       {
           Console.WriteLine(" the Occurance is " + t[i]);
       }
    }
    Console.ReadKey();

}

How can I do that with 2-D array also? Thanks.


Asked by:- LuneAgile
0
: 95 At:- 7/10/2018 1:58:43 PM
C# Array






2 Answers
profileImage Answered by:- jon

You can find duplicate array elements and count its occurence in 1 Dimentional array as given in below C# code

using System;
using System.Collections.Generic;
					
public class Program
{
	public 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)
		{
			if (dict.ContainsKey(value))
				dict[value]++;
			else
				dict[value] = 1;
		}
	
		foreach(var pair in dict)
			Console.WriteLine("Value {0} occurred {1} times.", pair.Key, pair.Value);
	   
	}
}

In the above code we are using Dictionary, output

Value 10 occurred 2 times.
Value 5 occurred 3 times.
Value 2 occurred 2 times.
Value 3 occurred 1 times.
Value 4 occurred 1 times.
Value 6 occurred 1 times.
Value 7 occurred 1 times.
Value 8 occurred 1 times.
Value 9 occurred 1 times.
Value 11 occurred 1 times.
Value 12 occurred 2 times.

For checking 2-D arrays, you can print the rows/columns with Duplicate values using Linq like below

using System;
using System.Linq;
					
public class Program
{
	public static void Main()
	{
		int[,] array = new int[5, 4] { 
			   { 1, 2,  3,  4 }, 
			   { 5, 5,  4,  5 },
			   { 9, 5,   5, 12 },
			   { 13, 14, 15, 16 }, 
			   { 17, 18, 19, 20 } 
		} ;
        
        for (int i = 0; i < 4; i++)
		{
			var row = Enumerable.Range(0, 4).Select(x => array[i, x]);
			if (row.Distinct().Count() != 4)
				Console.WriteLine("Duplicated value in row {0} : {1}", 
					i + 1, string.Join(", ", row));
		}
		
		for (int i = 0; i < 4; i++)
		{
			var column = Enumerable.Range(0, 4).Select(x => array[x, i]);
			if (column.Distinct().Count() != 4)
				Console.WriteLine("Duplicated value in column {0} : {1}", 
					i + 1, string.Join(", ", column));
		}
	}
	
}

Output

Duplicated value in row 2 : 5, 5, 4, 5
Duplicated value in row 3 : 9, 5, 5, 12
Duplicated value in column 2 : 2, 5, 5, 14
2
At:- 7/10/2018 3:40:23 PM


profileImage Answered by:- LuneAgile

Thanks so much Jon  : )  .

0
At:- 7/10/2018 4:34:22 PM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use