2

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?

Michael Liu
  • 44,833
  • 12
  • 104
  • 136
puretppc
  • 3,096
  • 7
  • 34
  • 63

1 Answers1

8

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).

Michael Liu
  • 44,833
  • 12
  • 104
  • 136
  • 1
    +1. It would be better to use Max-by-count to get `O(n)` for whole operation instead `O(n log n)` due to sorting - but there is no convenient on-line method in LINQ to do that (MoreLINQ have [MaxBy](http://stackoverflow.com/questions/19484563/morelinq-maxby-vs-linq-max-where) ) – Alexei Levenkov Nov 02 '13 at 02:34
  • @AlexeiLevenkov: Good point. The duplicated question has an O(n) algorithm which scans the list twice. – Michael Liu Nov 02 '13 at 02:44
  • The code worked but what if I don't need the InvalidOperationException since I don't need to check if the array is empty? What should I remove? – puretppc Nov 14 '13 at 18:13
  • @puretppc: If the array is empty, then technically there is no mode. What do you want the value of `mode` to be in that case? – Michael Liu Nov 14 '13 at 21:30