ivandrofly

count repeated / duplicated element in an array

Feb 15th, 2021 (edited)
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.84 KB | None | 0 0
  1.  
  2. // follow on github: https://github.com/ivandrofly
  3.  
  4. namespace FindDuplicatesElement
  5. {
  6.     using System;
  7.  
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             Console.WriteLine("Hello World!");
  13.  
  14.  
  15.             int[] list = { 1, 3, 1, 23, 4, 2, 2, 3, 3, 2, 3, 3, 32, 2, 2, 23, 45, 5, 5, 1, 2, 3, 4, 16, 61, 3, 4 };
  16.  
  17.             FindDuplicates(list);
  18.  
  19.             Console.ReadLine();
  20.         }
  21.  
  22.         private static void FindDuplicates(int[] a)
  23.         {
  24.             // [1, 2, 2, 3, 4,5,5,5]
  25.  
  26.             // # solution 1
  27.             // find max element in array
  28.             // create an array with the size of max
  29.             // for each number increment the index that number presend when a match is found
  30.  
  31.             int max = GetMax(a);
  32.  
  33.             // note: the +1 is that the array starts from 0 so it fix the out-of bound problem
  34.             int[] countArray = new int[max + 1];
  35.  
  36.             for (int i = 0; i < a.Length; i++)
  37.             {
  38.                 int item = a[i];
  39.                 countArray[item]++;
  40.             }
  41.  
  42.             for (int i = 0; i < countArray.Length; i++)
  43.             {
  44.                 if (countArray[i] > 0)
  45.                 {
  46.                     Console.WriteLine($"Value: {i} repeater: {countArray[i]}");
  47.                 }
  48.             }
  49.  
  50.             // # solution 2
  51.             // TODO: create a dictionary where key is the number found in list and increment the value accordingly when the key match in dictionary
  52.         }
  53.  
  54.         private static int GetMax(int[] array)
  55.         {
  56.             int max = array[0];
  57.  
  58.             for (int i = 1; i < array.Length; i++)
  59.             {
  60.                 if (array[i] > max)
  61.                 {
  62.                     max = array[i];
  63.                 }
  64.             }
  65.  
  66.             return max;
  67.         }
  68.     }
  69. }
  70.  
Add Comment
Please, Sign In to add comment