Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the Mode in Array C#? [duplicate]

Tags:

I want to find the Mode in an Array. I know that I have to do nested loops to check each value and see how often the element in the array appears. Then I have to count the number of times the second element appears. The code below doesn't work, can anyone help me please.

for (int i = 0; i < x.length; i ++) {     x[i]++;     int high = 0;     for (int i = 0; i < x.length; i++)     {         if (x[i] > high)         high = x[i];     } } 
like image 712
sarah Avatar asked Nov 24 '11 17:11

sarah


People also ask

What is the mode of an array?

Mode is the value which occurs most frequently in a set of observations. For example, {6, 3, 9, 6, 6, 5, 9, 3} the Mode is 6, as it occurs most often.

What is a mode in C?

A statistical term that refers to the most frequently occurring number found in a set of numbers. The mode is found by collecting and organizing the data in order to count the frequency of each result.


1 Answers

Using nested loops is not a good way to solve this problem. It will have a run time of O(n^2) - much worse than the optimal O(n).

You can do it with LINQ by grouping identical values and then finding the group with the largest count:

int mode = x.GroupBy(v => v)             .OrderByDescending(g => g.Count())             .First()             .Key; 

This is both simpler and faster. But note that (unlike LINQ to SQL) LINQ to Objects currently doesn't optimize the OrderByDescending when only the first result is needed. It fully sorts the entire result set which is an O(n log n) operation.

You might want this O(n) algorithm instead. It first iterates once through the groups to find the maximum count, and then once more to find the first corresponding key for that count:

var groups = x.GroupBy(v => v); int maxCount = groups.Max(g => g.Count()); int mode = groups.First(g => g.Count() == maxCount).Key; 

You could also use the MaxBy extension from MoreLINQ method to further improve the solution so that it only requires iterating through all elements once.

like image 97
Mark Byers Avatar answered Sep 28 '22 11:09

Mark Byers