Advertisement
nina75

Arrays/Task9

Dec 24th, 2013
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.68 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class MostFrequentNumber
  5. {
  6.     static void Main()
  7.     {
  8.         //Write a program that finds the most frequent number in an array.
  9.         //Example:  {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3} --> 4 (5 times)
  10.  
  11.         //Read the array
  12.         Console.Write("Enter the array's length: ");
  13.         int length = int.Parse(Console.ReadLine());
  14.         int[] array = new int[length];
  15.         Console.WriteLine("Enter the array's elements:");
  16.         for (int i = 0; i < length; i++)
  17.         {
  18.             array[i] = int.Parse(Console.ReadLine());
  19.         }
  20.  
  21.         //Solution
  22.         int bestCount = 1;
  23.         int currentCount = 0;
  24.         List<int> mostFrequents = new List<int>();
  25.  
  26.         for (int i = 0; i < array.Length - 1; i++)
  27.         {
  28.             if (array[i] == int.MinValue)
  29.             {
  30.                 continue;
  31.             }
  32.             currentCount = 1;
  33.             for (int j = i + 1; j < length; j++)
  34.             {
  35.                 if (array[i] == array[j])
  36.                 {
  37.                     currentCount++;
  38.                     array[j] = int.MinValue;
  39.                 }
  40.             }
  41.             if (currentCount > bestCount)
  42.             {
  43.                 bestCount = currentCount;
  44.                 mostFrequents.Clear();
  45.                 mostFrequents.Add(array[i]);
  46.             }
  47.             else if (currentCount == bestCount)
  48.             {
  49.                 mostFrequents.Add(array[i]);
  50.             }
  51.         }
  52.  
  53.         //Print the result
  54.         Console.WriteLine();
  55.         string str = string.Join(",", mostFrequents);
  56.         Console.WriteLine("{0} --> {1} times", str, bestCount);
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement