C# - Find the mode of numbers in an array


C# - Find the mode of numbers in an array

CODE
using System; using System.Collections.Generic; class Program { public static void Main() { //This program prints works for only 1 mode in a list of numbers. //This need to be tweaked, for more than 1 modes. int[] numbers = { 1, 3, 2, 5, 4, 6, 3, 5, 3, 5, 5 }; Dictionary<int, int> counts = new Dictionary<int, int>(); //The below loop will iterate through the numbers and store the number and its frequencies in the dictionary for(int i = 0; i < numbers.Length; i++) { int key = numbers[i]; if (counts.ContainsKey(key)) counts[key] = counts[key] + 1; else counts[key] = 1; } int max = int.MinValue; int mode = int.MinValue; //loop through the dictionary and find the max. foreach(int key in counts.Keys) { if (counts[key] > max) { max = counts[key]; mode = key; } } Console.WriteLine("The mode is {0}", mode); //OUTPUT //The mode is 5 Console.ReadKey(); } }

Comments