Advertisement
simonses

MostFreqNumber

Jan 10th, 2013
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.60 KB | None | 0 0
  1. using System;
  2.  
  3. class MostFreqNumber
  4. {
  5.     static void Main()
  6.     {
  7.         Console.WriteLine("Please, Insert the length of the array!");
  8.         int n = int.Parse(Console.ReadLine());
  9.  
  10.         // Read the array
  11.         int[] array = new int[n];
  12.  
  13.         for (int i = 0; i < n; i++)
  14.         {
  15.             array[i] = int.Parse(Console.ReadLine());
  16.         }
  17.  
  18.         // Example: {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3}  4 (5 times)
  19.         // Check the most frequent number
  20.         // Using Selection Sort
  21.         int currentMin;
  22.         int tempValue;
  23.  
  24.         for (int i = 0; i < array.Length - 1; i++)
  25.         {
  26.             currentMin = i;
  27.             for (int j = i + 1; j < array.Length; j++)
  28.             {
  29.                 if (array[j] < array[currentMin])
  30.                 {
  31.                     currentMin = j;
  32.                 }
  33.             }
  34.             tempValue = array[i];
  35.             array[i] = array[currentMin];
  36.             array[currentMin] = tempValue;
  37.         }
  38.        
  39.         // Count and Compair the lengths
  40.         int count = 0;
  41.         int getValue = 0;
  42.         int prnLength = 0;
  43.  
  44.         for (int i = 0; i < array.Length - 1; i++)
  45.         {
  46.             if (array[i] == array[i + 1])
  47.             {
  48.                 count++;
  49.             }
  50.             else
  51.             {
  52.                 count = 0;
  53.             }
  54.             if (count > prnLength)
  55.             {
  56.                 prnLength = count;
  57.                 getValue = array[i];
  58.             }
  59.         }
  60.  
  61.         // Print
  62.         Console.WriteLine("{0} ({1} times)", getValue, prnLength + 1);
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement