Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find duplicates 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();         }     } } 
like image 520
sunflower Avatar asked Dec 24 '13 18:12

sunflower


People also ask

How do I count occurrence of duplicate items in array?

To count the duplicates in an array:Copied! const arr = ['one', 'two', 'one', 'one', 'two', 'three']; const count = {}; arr. forEach(element => { count[element] = (count[element] || 0) + 1; }); // 👇️ {one: 3, two: 2, three: 1} console.

How do you find the number of repeating numbers in an array?

Method 1 (Basic)Use two loops. In the outer loop, pick elements one by one and count the number of occurrences of the picked element in the inner loop. This method doesn't use the other useful data provided in questions like range of numbers is between 1 to n and there are only two repeating elements.

How do you count duplicates in an array in Java?

For finding duplicates, Create a new List using original Arrays. Iterate through new List and remove elements by comparing elements in unique Arrays. Elements remaining in the new List will contain only duplicates.


1 Answers

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(); } 
like image 173
Reed Copsey Avatar answered Oct 14 '22 09:10

Reed Copsey