Advertisement
Klaxon

[C# Arrays] Most Frequent Number

Jul 15th, 2013
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.50 KB | None | 0 0
  1. // 9. Write a program that finds the most frequent number in an array.
  2. //    Example: {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3} -> 4 (5 times)
  3.  
  4. using System;
  5.  
  6. class MostFrequentNumber
  7. {
  8.     static void Main()
  9.     {
  10.         // create an array and get his size
  11.         Console.Write("Enter wanted array size: ");
  12.         int n = int.Parse(Console.ReadLine());
  13.         int[] array = new int[n];
  14.  
  15.         // help variables
  16.         int numerIndex = 0;
  17.         int currentCount = 1;
  18.         int bestCount = int.MinValue;
  19.  
  20.         // loop to fill up the array
  21.         for (int i = 0; i < n; i++)
  22.         {
  23.             array[i] = int.Parse(Console.ReadLine());
  24.         }
  25.         Array.Sort(array); // helps our counting
  26.  
  27.         // scan the array for similar numbers
  28.         for (int i = 0; i < n - 1; i++)
  29.         {
  30.             if (array[i] == array[i + 1])
  31.             {
  32.                 currentCount++;
  33.             }
  34.             else
  35.             {
  36.                 if (currentCount > bestCount)
  37.                 {
  38.                     bestCount = currentCount;
  39.                     numerIndex = array[i];
  40.                 }
  41.                 currentCount = 1;
  42.             }
  43.         }
  44.  
  45.         // exeptional case
  46.         if (currentCount > bestCount)
  47.         {
  48.             bestCount = currentCount;
  49.             numerIndex = array[array.Length - 1];
  50.         }
  51.  
  52.         // print the result
  53.         Console.WriteLine();
  54.         Console.WriteLine("{0} ({1} times)", numerIndex, bestCount);
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement