Advertisement
Teodor92

09. MostFreq

Jan 5th, 2013
520
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.32 KB | None | 0 0
  1. /* Write a program that finds the most frequent number in an array.
  2.  * Example:
  3.     {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3}  4 (5 times)
  4.  */
  5.  
  6. using System;
  7. using System.Collections.Generic;
  8.  
  9. class MostFrequent
  10. {
  11.     static void Main()
  12.     {
  13.         int[] myArray = { 4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3 };
  14.         Dictionary<int, int> mostFrequnet = new Dictionary<int, int>();
  15.         int bestElement = 0;
  16.         int bestFrequnecy = int.MinValue;
  17.         for (int i = 0; i < myArray.Length; i++)
  18.         {
  19.             //if (mostFrequnet.ContainsKey(myArray[i]))
  20.             //{
  21.             //    mostFrequnet[myArray[i]]++;
  22.             //}
  23.             //else
  24.             //{
  25.             //    mostFrequnet.Add(myArray[i], 1);
  26.             //}
  27.             int tempValue;
  28.             if (mostFrequnet.TryGetValue(myArray[i], out tempValue))
  29.             {
  30.                 mostFrequnet[myArray[i]] = tempValue + 1;
  31.             }
  32.             else
  33.             {
  34.                 mostFrequnet.Add(myArray[i], 1);
  35.             }
  36.         }
  37.         foreach (var item in mostFrequnet)
  38.         {
  39.             if (item.Value > bestFrequnecy)
  40.             {
  41.                 bestElement = item.Key;
  42.                 bestFrequnecy = item.Value;
  43.             }
  44.         }
  45.         Console.WriteLine("The number {0} shows {1} times", bestElement, bestFrequnecy);
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement