# Mode (most common element) of a list

Write a snippet to calculate the mode (most common number) of a list of positive integers.

For example, the mode of

d = [4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8]


is 1, because it occurs the maximum of 5 times.

You may assume that the list is stored in a variable such as d and has a unique mode.

e.g.: Python, 49

max(((i,d.count(i))for i in set(d)), key=lambda x:x)


This is , so the shortest solution in bytes wins.

# K5, 6 bytes

*>#:'=


The first (*) of the descending elements (>) of the count of each (#:') of the group (=). Step by step:

  i
4 3 1 0 6 1 6 4 4 0 3 1 7 7 3 4 1 1 2 8

=i
4 3 1 0 6 7 2 8!(0 7 8 15
1 10 14
2 5 11 16 17
3 9
4 6
12 13
,18
,19)

#:'=i
4 3 1 0 6 7 2 8!4 3 5 2 2 2 1 1

>#:'=i
1 4 3 7 6 0 8 2

*>#:'=i
1


## Python 2 - 18

max(d,key=d.count)


Since your python answer doesn't seem to print, I expect this is what you want.

Add 6 bytes for print normally.

• perfect, think @globby needs to see future :) – garg10may Dec 19 '14 at 16:25
• The great thing about this one is that it's not even golfy, it's just Pythonic. The only thing that's been golfed is a space between d, and key=. – wchargin Dec 19 '14 at 17:28
• @WChargin: Eh, Pythonic would be to avoid the quadratic runtime by using defaultdict(int) or Counter. Something like Counter(d).most_common(). – user2357112 supports Monica Dec 21 '14 at 3:01

# Matlab/Octave, 7 5 bytes

Unsurprisingly there's a built-in function for finding modes. As an anonymous function:

@mode


This returns the most commonly occuring element in the input vector with ties going to the smaller value.

Saved 2 bytes thanks to Dennis!

• +1, clearly the right tool for the job. As it's a builtin, what happens if there's more than one number of highest frequency? – Level River St Dec 20 '14 at 10:55
• @steveverrill According to the documentation (type help mode): "If two, or more, values have the same frequency 'mode returns the smallest." – wchargin Dec 21 '14 at 3:05
• Unnamed functions seem to be allowed (the accepted answer is one), so you could shorten this to @mode. – Dennis Jun 2 '16 at 23:41
• @Dennis Thanks! Though I admit it's a strange feeling to edit my first answer on the site. – Alex A. Jun 3 '16 at 5:18

## Pyth - 6

eo/QNQ


Try it online.

Expects input on stdin like [4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8]. Ties are resolved by last occurrence because Python performs stable sorts.

Sorts the list by count the value in the list, then prints the last number of the list.

Q could be replaced with d if you initialized d to contain the value before e.g. =d[4 3 1 0 6 4 4 0 1 7 7 3 4 1 1 2 8)

Python-esque pseudo-code:

Q=eval(input());print(sorted(Q,key=Q.count)[-1])


Full Explanation:

            : Q=eval(input()) (implicit)
e           : ... [-1]
o   Q      : orderby(lambda N: ...,Q)
/QN       : count(Q,N)


Pyth's orderby runs exactly like Python's sorted with orderby's first argument being the key argument.

# Mathematica, 25 bytes

Last@SortBy[d,d~Count~#&]


or

#&@@SortBy[d,-d~Count~#&]


As in the challenge, this expects the list to be stored in d.

## or... 15 bytes

Of course, Mathematica wouldn't be Mathematica if it didn't have a built-in:

#&@@Commonest@d


Commonest returns a list of all most common elements (in case of a tie), and #&@@ is a golfed First@.

• another case for mthmca – Michael Stern Apr 13 '16 at 19:26

# Ruby, 22 bytes

d.max_by{|i|d.count i}


Basically a port of my Mathematica answer, except Ruby has a direct max_by so I don't need to sort first.

• I was about to suggest d.max_by d.method:count but that's about a million (aka not even two) bytes longer. Still, it's worth noting that it's possible. – Fund Monica's Lawsuit May 10 '16 at 18:39

# R, 33 25 bytes

Thanks @Hugh for the help shortening:

names(sort(-table(d)))


The original:

v=table(d);names(v[which.max(v)])


This calculates the frequency of each element in the vector d, then returns the name of the column containing the largest value. The value returned is actually a character string containing the number. It didn't say anywhere that that wasn't okay, so...

Any suggestions to shorten this are welcome!

• names(sort(-table(d))) – Hugh Dec 20 '14 at 8:21

# CJam, 11 10 bytes

A{A\-,}$0=  Assumes the array in a variable called A. This is basically sorting the array based on the occurrence of each number in the array and then picks the last element of the array. Example usage [1 2 3 4 4 2 6 6 6 6]:A;A{aA\/,}$W=


Output

6


1 byte saved thanks to Dennis!

Try it online here

• A{A\-,}$0= is one byte shorter. – Dennis Dec 31 '14 at 2:47 • As of 0.6.5 it's doable in 8 bytes: Ae$e_W= – Martin Ender Jun 3 '15 at 0:09
• @MartinEnder Umm... nope. I knew you need to sort first. – Erik the Outgolfer Dec 12 '16 at 18:27
• @ErikGolferエリックゴルファー whoops, you're right, needs 9 bytes: $e$e_W= – Martin Ender Dec 12 '16 at 18:30

# Powershell 19

($d|group).Count  (this asumes the array is already on $d)

# J - 12 char

Anonymous function. Sorts list from most to least common, taking first item.

(0{~.\:#/.~)

• 0{ First of
• ~. Unique items
• \: Downsorted by
• #/.~ Frequencies

Try it for yourself.

• This is really 10 bytes--the function can be assigned without the parens. – Conor O'Brien May 12 '16 at 21:20

# JavaScript (ES6) 51

Just a single line expression using the preloaded variable d. Sort the array by frequency then get the first element.
Nasty side effect, the original array is altered

d.sort((a,b)=>d.map(w=>t+=(w==b)-(w==a),t=0)&&t)


As usual, using .map instead of .reduce because it's 1 char shorter overall. With .reduce it' almost a clean, non-golfed solution.

d.sort((a,b)=>d.reduce((t,w)=>t+(w==b)-(w==a),0))


At last, a solution using a function, not changing the original array and without globals (62 bytes):

F=d=>[...d].sort((a,b)=>d.reduce((t,w)=>t+(w==b)-(w==a),0))


Test In FireFox/FireBug console

d=[4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8]
d.sort((a,b)=>x.map(w=>t+=(w==b)-(w==a),t=0)&&t)


Output 1

The d array becomes:

[1, 1, 1, 1, 1, 4, 4, 4, 4, 3, 3, 3, 0, 6, 6, 0, 7, 7, 2, 8]


# Python - 32

max((x.count(i),i)for i in x)


Don't see an 18 character solution anywhere in the future to be honest.

EDIT: I stand corrected, and impressed.

# JavaScript, ES6, 71 bytes

A bit long, can be golfed a lot.

f=a=>(c=b=[],a.map(x=>b[x]?b[x]++:b[x]=1),b.map((x,i)=>c[x]=i),c.pop())


This creates a function f which can be called like f([1,1,1,2,1,2,3,4,1,5]) and will return 1.

Try it on your latest Firefox's Console.

• Off-topic, but I just realized how relevant your username is to PCG.SE. :P – nyuszika7h Dec 20 '14 at 11:16
• @nyuszika7h heh. Although I have had this username long before I even know PPCG existed. – Optimizer Dec 20 '14 at 11:20
• f=a=>(c=b=[],a.map(x=>b[x]++-1?0:b[x]=1),b.map((x,i)=>c[x]=i),c.pop()) is 1 byte shorter. – Bálint May 11 '16 at 5:59

# 05AB1E, 3 bytes

(non-competing - question predates the language)

.MJ


Explanation:

.M  # Gets the most frequent element in the [implicit] input
J # Converts to a string, needed as the program would output "" instead of "1" without this.


If you want to store the array in a variable instead of using input, just push the array to the stack at the start of the program.

Try it online!

# C# - 49

Can't really compete using C# but oh well:

Assuming d is the array

d.GroupBy(i=>i).OrderBy(a=>a.Count()).Last().Key;

# bash - 29 27 characters

sort|uniq -c|sort -nr|sed q


Using it:

sort|uniq -c|sort -nr|sed q
4
3
1
0
6
1
6
4
4
0
3
1
7
7
3
4
1
1
2
8
[ctrl-D]
5 1


i.e. "1" is the mode, and it appears five times.

• sort|uniq -c|sort -nr|sed q saves a couple of characters – Digital Trauma Dec 19 '14 at 20:06
• I posted the same answer, but you were faster :) – pgy Dec 19 '14 at 20:10
• @pgy - thank you - have updated! – user15259 Dec 19 '14 at 20:25

# GolfScript, 10 bytes

say .Bag.invert.max.value; # implicitly calls $_.Bag…  If there is a tie it will print the larger of the ones that tied. The .Bag method on a List or an Array creates a quantified hash that associates the total count of how many times a given value was seen with that value. bag(4(4), 3(3), 1(5), 0(2), 6(2), 7(2), 2, 8)  The .invert method creates a List of the pairs in the bag with the key and the value swapped. ( The reason we call this is for the next method to do what we want ) 4 => 4, 3 => 3, 5 => 1, 2 => 0, 2 => 6, 2 => 7, 1 => 2, 1 => 8  The .max method on a List of Pairs returns the biggest Pair comparing the keys first and in the case of a tie comparing the values. ( This is because that is how multi infix:<cmp>(Pair:D \a, Pair:D \b) determines which is larger ) 5 => 1  The .value method returns the value from the Pair. ( It would have been the key we were after if it wasn't for the .invert call earlier ) 1  If you want to return all of the values that tied in the case of a tie: say @list.Bag.classify(*.value).max.value».key  The .classify method returns a list of pairs where the keys are from calling the Whatever lambda *.value with each of the Pairs. 1 => [2 => 1, 8 => 1], 2 => [0 => 2, 6 => 2, 7 => 2], 3 => [3 => 3], 4 => [4 => 4], 5 => [1 => 5]  Then we call .max to get the largest Pair. "5" => [1 => 5]  A call to .value gets us the original Pairs from the Bag ( just one in this case ) 1 => 5  Then we use >>.key to call the .key method on every Pair in the list, so that we end up with a list of the values that were seen the most. 1  ## Java 8 : 184 bytes Stream.of(A).collect(Collectors.groupingBy(i -> i, Collectors.counting())).entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).findFirst().get().getKey();  Input A must be of type Integer[]. Note java.util.* and java.util.stream.* need to be imported, however in the spirit oneliner they are left out. • downvoting because of ... ? – PoweredByRice Jan 4 '15 at 20:56 • I know it's been more than two years, but you can remove the spaces at (i->i,Collectors.counting()). – Kevin Cruijssen Feb 1 '17 at 12:18 # Bash + unix tools, 62 bytes Expects the array in the STDIN. The input format does not count, as long as the numbers are non-negative integers. grep -o [0-9]\*|sort|uniq -c|sort -n|awk 'END{print$2}'


Edited: escaped wildcard in grep argument. Now it can be run safely in non-empty directories. Thanks to manatwork.

• Best if run in an empty directory. Otherwise [0-9]* may get expanded to matching file names. – manatwork Nov 29 '15 at 13:26
• Alternatively, put ' around the argument to grep. – Paŭlo Ebermann Nov 29 '15 at 19:41

# Perl, 27 bytes

$Q[$a{$_}++]=$_ for@F;pop@Q


Returns the last most common value in case of a tie.

# PHP, 53 50 bytes

<?=array_flip($c=array_count_values($d))[max($c)];  Run like this: echo '<?php$d=$argv;?><?=array_flip($c=array_count_values($d))[max($c)]; echo"\n";' | php -- 4 3 1 0 6 1 6 4 4 0 3 1 7 7 3 4 1 1 2 8


## Tweaks

• Saved 3 bytes by making use of the freedom to assume the input is assigned to a variable d

# Java 8, 83 Bytes

d.stream().max((x,y)->Collections.frequency(d,x)-Collections.frequency(d,y)).get();


d must be a Collection<Integer>.

If Collections can be statically imported:
59 Bytes

d.stream().max((x,y)->frequency(d,x)-frequency(d,y)).get();


import Data.List
import Data.Ord


If the imports are ignored, it's 45.

• You can save 4 bytes by using point-free style and 2 bytes by using maximumBy instead of last.sortBy. The new code would become g=head.maximumBy(comparing length).group.sort. – Hjulle Nov 28 '17 at 15:54
• 1.) Anonymous functions are allowed, so you can drop the g=. 2.) You can replace maximumBy(comparing length) by snd.maximum.map((,)=<<length) which doesn't need to import Ord, for a total of 62 bytes: Try it online! – Laikoni Nov 29 '17 at 11:08

f s=snd\$maximum[([1|y<-s,y==x],x)|x<-s]


Try it online!

Edit: Thans to Zgarb for -3 bytes

• I think sum is unnecessary here. – Zgarb Nov 29 '17 at 11:44
• @Zgarb Right, I actually used exactly the same trick in a previous answer. Thanks for reminding me! – Laikoni Nov 29 '17 at 15:03

# Brachylog, 5 bytes

ọtᵒth


Try it online!

This isn't really a snippet, but I'm not sure what would be...

         The output is
h    the first element of
t     the last element of
ọ        a list of [value, number of occurrences] pairs corresponding to
the input,
ᵒ      sorted ascending by
t       their last elements (the numbers of occurrences).

• It fails for negative input – garg10may Jun 13 '19 at 3:43
• @garg10may Use an underscore instead of a hyphen, it should work that way – Unrelated String Jun 13 '19 at 4:52

## Clojure, 32 bytes

#(apply max-key(frequencies %)%)


(frequencies %) returns a hash-map, which can be used as a function. Given a key it returns the corresponding value :)

Equal length:

#(last(sort-by(frequencies %)%))


# Scala, 32

d.groupBy(a=>a).maxBy(_._2.size)


## C++ 119

int *a=std::max_element(x,x+n);int z=0,b=0,c=0;for(int i=0;i<=*a;i++){c=std::count(x,x+n,i);if(c>b){b=c;z=i;}}return z;


Full code and test:

#include <iostream>
#include <algorithm>
#include <vector>

int m(int *x,int n)
{
int *a=std::max_element(x,x+n);int z=0,b=0,c=0;for(int i=0;i<=*a;i++){c=std::count(x,x+n,i);if(c>b){b=c;z=i;}}return z;
}

int main()
{
int d[] = {4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8};
std::cout<<m(d,20);
return 0;
}
`