Question

Here is my array:

int myArray = new int[5];

myArray[0] = 1;
myArray[1] = 1;
myArray[2] = 1;
myArray[3] = 3;
myArray[4] = 5;

What do I have to write if I want the program to find the mode of this array?

Was it helpful?

Solution

Here's a LINQ solution:

int mode = myArray
    .GroupBy(x => x)
    .OrderByDescending(g => g.Count())
    .First() // throws InvalidOperationException if myArray is empty
    .Key;

This groups the elements of myArray by value, sorts the groups by the number of values in each group, and takes the value of the first group. If there is more than one mode, then this takes whichever one occurs first (has the lowest index) in myArray.

If there might be more than one mode and you need all of them, then you can use this variation instead:

var groups = myArray
    .GroupBy(x => x)
    .Select(g => new { Value = g.Key, Count = g.Count() })
    .ToList(); // materialize the query to avoid evaluating it twice below
int maxCount = groups.Max(g => g.Count); // throws InvalidOperationException if myArray is empty
IEnumerable<int> modes = groups
    .Where(g => g.Count == maxCount)
    .Select(g => g.Value);

This groups the elements of myArray by value, finds the maximum number of values in any group, and takes the value of every group having that maximum number of values.

If myArray is very large, then the second version (which is O(n)) might be faster than the first version (which is O(n log n) due to the sort).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top