26
\$\begingroup\$

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

This is , so the shortest solution in bytes wins.

\$\endgroup\$

35 Answers 35

1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

Pyke, 10 bytes

(non-competing), language newer than challenge

D3m/DSe@R@

Try it here!

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

Jelly, 7 bytes (non-competing)

ṢŒrṪÞṪṪ

Try it online!

Longer than K :(

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

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.