g | x | w | all
Bytes Lang Time Link
043AWK250902T154238Zxrs
001Thunno 2230719T143101ZThe Thon
045JavaScript Node.js230221T183602Zl4m2
002Nekomata230701T003030Zalephalp
037Julia 1.0230220T223330ZAshlin H
510Nibbles230221T230650ZDominic
nan230221T190056ZThe Thon
005Japt h230221T110527ZShaggy
055Zsh builtins only201210T040912Zroblogic
032Arturo230220T210027Zchunes
010Pyke160508T124945ZBlue
00205AB1E201209T213836ZMakonede
00305AB1E170201T102732ZOkx
007Jelly161212T183141ZErik the
002Jelly201207T180018Zcaird co
032Clojure190613T124053ZNikoNyrh
005Brachylog190612T220858ZUnrelate
039Haskell171129T112903ZLaikoni
078Haskell150101T043001Zuser3202
083Java 8141231T100810Zc.P.u1
050PHP160603T085134Zaross
005Matlab/Octave141219T184623ZAlex A.
067Ceylon151129T124034ZPaŭlo Eb
021Perl 6141229T164946ZBrad Gil
029jq160511T105059Zmanatwor
027Perl160510T121506ZTon Hosp
062Bash + unix tools141219T200021Zpgy
094Hassium151130T174027ZJacob Mi
006K5151129T204403ZJohnE
006Pyth141219T161110ZFryAmThe
010CJam141219T161006ZOptimize
012Dyalog APL141231T004314Zngn
119C++141230T223803Zbacchusb
184Java 8141229T194636ZPoweredB
032Scala141223T175757ZChad Ret
051JavaScript ES6141221T200659Zedc65
025R141219T182759ZAlex A.
010GolfScript141220T214753ZIlmari K
071JavaScript141220T085030ZOptimize
012J141220T070912Zalgorith
027bash141219T194838Zuser1525
049C#141219T183126ZBrandon
019Powershell141219T181406ZDarkAjax
032Python141219T155802Zglobby
022Ruby141219T162510ZMartin E
018Python 2141219T161920ZFryAmThe
025Mathematica141219T160752ZMartin E

AWK, 43 bytes

{for(;i++<NF;)m<++b[$i]&&m=b[$i]&&a=$i}$0=a

Attempt This Online!

Thunno 2, 1 byte

Try it online!

Built-in.

JavaScript (Node.js), 45 bytes

x=>x.map(a=t=>a[t]=0+a[t]||[1+t]).sort()[0]-1

Try it online!

42 without 0 support

Nekomata, 2 bytes

ŢṂ

Attempt This Online!

Ţ   Tally
 Ṃ  Maximum by

Let's take the input [4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8] as an example.

Ţ returns two lists [4,3,1,0,6,7,2,8] and [4,3,5,2,2,2,1,1], where the first list contains the unique elements of the input, and the second list contains the number of occurrences of each element.

finds an element in the first list with the largest corresponding element in the second list, and returns that element. In this case, the maximum of the second list is 5, and the corresponding element in the first list is 1, so returns 1.

Julia 1.0, 39 37 bytes

~d=argmax(@.sum(==(1:max(d...)),[d]))

Try it online!

The solution above works for positive integers. It can be adapted to handle 0:

Julia 1.0, 41 39 bytes

~d=argmax(@.sum(==(0:max(d...)),[d]))-1

Try it online!

-2 bytes thanks to MarcMush: use sum instead of count

Nibbles, 5 bytes (10 nibbles)

/+=~$,+`%@
  =~        # group and sort
    $       # the input
            # by
     ,      #   length of
      +     #   flattened
       `%   #   split
         @  #   the input
            #   by
            #   (implicitly) each element  
 +          # then flatten this
/           # and output the first element 
            # (by folding over list returning left-hand
            # argument at each step)     

enter image description here

Thunno, \$ 11 \log_{256}(96) \approx \$ 9.05 bytes

ztcZZz;AJAK

Attempt This Online!

Thunno doesn't have a mode built-in so we have to implement it ourselves:

ztcZZz;AJAK  # Implicit input
zt           # Triplicate the (implicit) input
  c          # And get the count of each element
   ZZ        # Zip with the input
             # So we have a nested list of the form
             # [[count, element], [count, element], ...]
     z;      # And reverse-sort this list of lists
             # (so the first pair will be the mode)
       AJ    # Get the first pair
         AK  # And get the last item
             # Implicit output

Japt -h, 5 bytes

ü ñÊÌ

Try it

ñ@è¶X

Try it

ü ñÊÌ     :Implicit input of array
ü         :Group & sort
  ñ       :Sort by
   Ê      :  Length
    Ì     :Last element
          :Implicit output of last element
ñ@è¶X     :Implicit input of array
ñ         :Sort by
 @        :Passing each X through the following function
  è       :  Count the elements in U
   ¶X     :    Equal to X
          :Implicit output of last element

Zsh (builtins only), 55 57 62 bytes

for i ({0..9})c=${#${(M)A#$i}}&&((c>d?(d=c,m=i)));<<<$m

Try it online!   57B

No utils like sort, uniq, sed. Uses data from array A. The expression ${#${(M)A#$i}} counts elements of A, matching pattern $i. Then we just keep track of the biggest $c and matching $i. (note, Zsh is triggered by c>d?..., just ignore the guff on stderr)


Alternate, regex-ified solution, for 80B.

B+=(${(Mj::)A#$i}) constructs an array B with all ith elements joined, so in the given example the element 11111 is the longest.

for i ({0..9})B+=(${(Mj::)A#$i})
<<<${B[(r)${(l.${#${(O@)B//?/X}[1]}..?.)}]:1:1}

Sample code taken from the Zsh User Guide. Quote: "This chapter will appeal above all to people who are excited by the fact that print ${array[(r)${(l.${#${(O@)array//?/X}[1]}..?.)}] prints out the longest element of the array $array [...] This is for advanced students only (nutcases, if you ask me)."
PS: Here's a slightly more sensible way for 69B

Arturo, 32 bytes

$=>[m:maximum tally&[k,v][v]m\0]

Try it

Pyke, 10 bytes

D3m/DSe@R@

Try it here!

05AB1E, 2 bytes

.M

Try it online!

05AB1E, 3 bytes

.MJ

Explanation:

.M  # Gets the most frequent element in the [implicit] input
  J # Converts to a string, needed as the program would output "[1]" 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!

Jelly, 7 bytes

ṢŒrṪÞṪṪ

Try it online!

Longer than K :(

Assumes the first argument has the array. There are no variables in Jelly.

Jelly, 2 bytes

Æṃ

Try it online!

Jelly finally got a mode builtin! A non-builtin version however is 5 bytes:

ċ@Þ`Ṫ

Try it online!

How they work

Æṃ - Main link. Takes a list d on the left
Æṃ - Return the mode of d

Well that was unimpressive. How about the 5 byte, non-builtin version?

ċ@Þ`Ṫ - Main link. Takes d on the left
   `  - Use d as both the left and right argument to:
  Þ   -   Sort d by:
ċ@    -     Count occurrences in d
    Ṫ - Take the last element (i.e. the element with a maximal count in d)

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

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

Haskell, 42 39 bytes

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

Try it online!

Edit: Thans to Zgarb for -3 bytes

Haskell 78

import Data.List
import Data.Ord
g=head.maximumBy(comparing length).group.sort

If the imports are ignored, it's 45.

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();

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

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!

Ceylon, 67

E m<E>(E+l)=>(l.frequencies().max(increasingItem)else nothing).key;

This function works on any type of element, including Integers (though null elements are ignored). (And it is shorter than the same function for just integers.)

Formatted:

E m<E>(E+ l) =>
        (l
        .frequencies()
        .max(increasingItem)
            else nothing)
    .key;

The else nothing is needed, because the Ceylon compiler can't figure out that l.frequencies always is non-empty if l is nonempty (because in general, all elements of l could be null, and therefore discarded).

You can call this function like this:

print(m(4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8));

If you already have a list list, call it like this:

print(m(*list));

(This will unpack the list into arguments, and pass them to the function.)

Perl 6, 21 bytes

.Bag.invert.max.value

Example:

$_ = < 4 3 1 0 6 1 6 4 4 0 3 1 7 7 3 4 1 1 2 8 >».Int;

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

jq, 29 characters

group_by(.)|max_by(length)[0]

Sample run:

bash-4.3$ jq 'group_by(.)|max_by(length)[0]' <<< '[4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8]'
1

On-line test

Perl, 27 bytes

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

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

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.

Hassium, 94 Bytes

This example assumes that the array is stored in d

func main(){t,b=0;foreach(e in d){c=0;foreach(n in d)if(e==n)c++;if(c>b){b=c;t=e;}}println(t)}

See expanded and run online with test case here

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

try it in your browser!

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.

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

Dyalog APL, 12 characters

d[⊃⍒+/∘.=⍨d]

∘.=⍨d is the same as d∘.=d, reflexive outer product of =. It creates a boolean matrix comparing every pair of elements in d.

+/ sums that matrix along one of the axes and produces a vector.

grades the vector, i.e. sorts it by indices. (As the glyphs suggest, grades in descending order and would grade in ascending order.)

takes the first index from the grading—the index of the largest element of d.

d[...] returns that element.

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;
}

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.

Scala, 32

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

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)[0]

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))[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))[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)[0]

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]

R, 33 25 bytes

Thanks @Hugh for the help shortening:

names(sort(-table(d))[1])

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!

GolfScript, 10 bytes

a{a\-,}$0=

From this answer I wrote to Tips for golfing in GolfScript. Expects the input in an array named a, returns result on stack. (To read input from an array on the stack, prepend : for 11 bytes; to read input from stdin (in the format [1 2 1 3 7]), also prepend ~ for 12 bytes.)

This code works by iterating over the input array, subtracting each element from the original array, and counting the number of elements left. This is then used as a key to sort the original array by, and the first element of the sorted array is returned.

Online demo.

Ps. Thanks to Peter Taylor for pointing out this challenge to me.

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.

J - 12 char

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

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

Try it for yourself.

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.

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;

Powershell 19

($d|group)[0].Count

(this asumes the array is already on $d)

Python - 32

max((x.count(i),i)for i in x)[1]

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

EDIT: I stand corrected, and impressed.

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.

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.

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