SHARE
TWEET

09. MostFreq

Teodor92 Jan 5th, 2013 455 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top