Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- class MostFrequentNumber
- {
- static void Main()
- {
- //Write a program that finds the most frequent number in an array.
- //Example: {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3} --> 4 (5 times)
- //Read the array
- Console.Write("Enter the array's length: ");
- int length = int.Parse(Console.ReadLine());
- int[] array = new int[length];
- Console.WriteLine("Enter the array's elements:");
- for (int i = 0; i < length; i++)
- {
- array[i] = int.Parse(Console.ReadLine());
- }
- //Solution
- int bestCount = 1;
- int currentCount = 0;
- List<int> mostFrequents = new List<int>();
- for (int i = 0; i < array.Length - 1; i++)
- {
- if (array[i] == int.MinValue)
- {
- continue;
- }
- currentCount = 1;
- for (int j = i + 1; j < length; j++)
- {
- if (array[i] == array[j])
- {
- currentCount++;
- array[j] = int.MinValue;
- }
- }
- if (currentCount > bestCount)
- {
- bestCount = currentCount;
- mostFrequents.Clear();
- mostFrequents.Add(array[i]);
- }
- else if (currentCount == bestCount)
- {
- mostFrequents.Add(array[i]);
- }
- }
- //Print the result
- Console.WriteLine();
- string str = string.Join(",", mostFrequents);
- Console.WriteLine("{0} --> {1} times", str, bestCount);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement