stkirov

09.MostFrequentElement

Jan 5th, 2013
456
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.91 KB | None | 0 0
  1. //Write a program that finds the most frequent number in an array. Example:
  2. //  {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3}  4 (5 times)
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6.  
  7. class MostFrequentElement
  8. {
  9.     static void Main()
  10.     {
  11.         int[] array = {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3};
  12.  
  13.         Dictionary<int, int> elementsInArray = new Dictionary<int, int>();
  14.  
  15.         for (int i = 0; i < array.Length; i++)
  16.         {
  17.             if (elementsInArray.ContainsKey(array[i]))
  18.             {
  19.                 elementsInArray[array[i]]+=1;
  20.             }
  21.             else
  22.             {
  23.                 elementsInArray.Add(array[i], 1);
  24.             }
  25.         }
  26.         int number = elementsInArray.Aggregate((x, y) => x.Value > y.Value ? x : y).Key;
  27.         int count = elementsInArray.Max(x=>x.Value);
  28.         Console.WriteLine("{0} ({1} times)", number, count);
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment