Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the most common (frequent) string entry in array

Tags:

arrays

c#

I have a string array with values in it (duh...).

Is there an easy way of getting the entry which occurs the most? Something like

values[37].getMostOften();

Cheers :)

like image 494
Andy Avatar asked Nov 06 '13 23:11

Andy


People also ask

How would you find the most frequent string in an array?

A simple solution is to run two loops and count occurrences of every word. Time complexity of this solution is O(n * n * MAX_WORD_LEN).

How do you find the most repeated item in an array?

A simple solution is to run two loops. The outer loop picks all elements one by one. The inner loop finds the frequency of the picked element and compares it with the maximum so far.

How do I find the most common number in an array Python?

Make use of Python Counter which returns count of each element in the list. Thus, we simply find the most common element by using most_common() method.

How do I find the most frequent element in an array in NumPy?

Steps to find the most frequency value in a NumPy array: Create a NumPy array. Apply bincount() method of NumPy to get the count of occurrences of each element in the array. The n, apply argmax() method to get the value having a maximum number of occurrences(frequency).


1 Answers

You can use GroupBy:

var mostCommonValue = values.GroupBy(v => v)
                            .OrderByDescending(g => g.Count())
                            .Select(g => g.Key)
                            .FirstOrDefault();
like image 108
Reed Copsey Avatar answered Nov 05 '22 22:11

Reed Copsey