Averages/Mode: Difference between revisions

m
imported>Arakov
 
(46 intermediate revisions by 26 users not shown)
Line 1:
{{task|Probability and statistics}}
 
;Task
{{task heading}}
 
Write a program to find the [[wp:Mode (statistics)|mode]] value of a collection.
Line 15:
<hr>
 
=={{Headerheader|ActionScript11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">F modes(values)
DefaultDict[Int, Int] count
L(v) values
count[v]++
V best = max(count.values())
R count.filter(kv -> kv[1] == @best).map(kv -> kv[0])
 
print(modes([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]))
print(modes([1, 1, 2, 4, 4]))</syntaxhighlight>
{{out}}
<pre>
[6]
[1, 4]
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE MAX="100"
INT ARRAY keys(MAX)
INT ARRAY values(MAX)
BYTE count
 
PROC PrintArray(INT ARRAY a INT size)
INT i
 
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
 
PROC ClearMap()
count=0
RETURN
 
PROC AddToMap(INT a)
INT i,index
 
index=-1
IF count>0 THEN
FOR i=0 TO count-1
DO
IF keys(i)=a THEN
index=i EXIT
FI
OD
FI
IF index=-1 THEN
keys(count)=a
values(count)=1
count==+1
ELSE
values(index)==+1
FI
RETURN
 
PROC Mode(INT ARRAY a INT aSize INT ARRAY m INT POINTER mSize)
INT i,mx
 
ClearMap()
FOR i=0 TO aSize-1
DO
AddToMap(a(i))
OD
 
mx=0
FOR i=0 TO count-1
DO
IF values(i)>mx THEN
mx=values(i)
FI
OD
 
mSize^=0
FOR i=0 TO count-1
DO
IF values(i)=mx THEN
m(mSize^)=keys(i)
mSize^==+1
FI
OD
RETURN
 
PROC Test(INT ARRAY a INT size)
INT ARRAY m(MAX)
INT mSize
 
PrintE("Array:") PrintArray(a,size)
Mode(a,size,m,@mSize)
PrintE("Mode:") PrintArray(m,mSize)
PutE()
RETURN
 
PROC Main()
INT ARRAY a=[1 3 5 7 3 1 3 7 7 3 3]
INT ARRAY b=[7 13 5 13 7 2 7 10 13]
INT ARRAY c=[5]
 
Test(a,11)
Test(b,9)
Test(c,1)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Mode.png Screenshot from Atari 8-bit computer]
<pre>
Array:
[1 3 5 7 3 1 3 7 7 3 3]
Mode:
[3]
 
Array:
[7 13 5 13 7 2 7 10 13]
Mode:
[7 13]
 
Array:
[5]
Mode:
[5]
</pre>
 
=={{header|ActionScript}}==
This implementation does not work with arbitrary collections. However, it works with arrays containing mixed data, including strings and other arrays.
<langsyntaxhighlight ActionScriptlang="actionscript">function Mode(arr:Array):Array {
//Create an associative array to count how many times each element occurs,
//an array to contain the modes, and a variable to store how many times each mode appears.
Line 44 ⟶ 169:
}
return modeList;
}</langsyntaxhighlight>
 
=={{Headerheader|Ada}}==
{{works with|Ada 2005}}
mode.ads:
<langsyntaxhighlight Adalang="ada">generic
type Element_Type is private;
type Element_Array is array (Positive range <>) of Element_Type;
Line 56 ⟶ 181:
function Get_Mode (Set : Element_Array) return Element_Array;
 
end Mode;</langsyntaxhighlight>
mode.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Containers.Indefinite_Vectors;
 
package body Mode is
Line 159 ⟶ 284:
end Get_Mode;
 
end Mode;</langsyntaxhighlight>
example use:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Mode;
procedure Main is
Line 186 ⟶ 311:
end loop;
Ada.Text_IO.New_Line;
end Main;</langsyntaxhighlight>
{{out}}
<pre>Input: 1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6
Result: 2, 3</pre>
 
=={{Headerheader|APLALGOL 68}}==
{{libheader|ALGOL 68-rows}}
<lang APL>mode←{{s←⌈/⍵[;2]⋄⊃¨(↓⍵)∩{⍵,s}¨⍵[;1]}{⍺,≢⍵}⌸⍵}</lang>
This sample defines an operator to return the mode(s) of an integer array. Additional operators cound be defined for other array types.
<br>Note the source of rows.incl.a68 (containing the QUICKSORT and SHOW operators) is available on a page in Rosetta Code, see the above link.
<syntaxhighlight lang="algol68">
BEGIN # find the mode (most frequent value) of a set of items #
PR read "rows.incl.a68" PR # include row (array) utilities #
# returns the mode(s) of a - similar operators could be defined for #
# types other than INT #
OP MODEOF = ( []INT a )[]INT:
IF LWB a > UPB a THEN []INT() # no data #
ELSE # have data #
[ LWB a : UPB a ]INT sorted data := a;
QUICKSORT sorted data FROMELEMENT LWB sorted data TOELEMENT UPB sorted data;
INT distinct count = BEGIN # count the number of distinct values #
INT count := 1;
INT value := sorted data[ LWB sorted data ];
FOR i FROM LWB sorted data + 1 TO UPB sorted data DO
IF value /= sorted data[ i ] THEN
count +:= 1;
value := sorted data[ i ]
FI
OD;
count
END;
INT current value := sorted data[ LWB sorted data ];
INT max count := 0;
INT current count := 1;
INT s pos := LWB sorted data + 1;
# allow for the maximum possible number of modes #
[ 1 : distinct count ]INT modes;
INT mode count := 1;
modes[ 1 ] := current value;
WHILE s pos <= UPB sorted data DO
s pos +:= 1;
WHILE IF s pos > UPB sorted data
THEN FALSE
ELSE sorted data[ s pos ] = current value
FI
DO
current count +:= 1;
s pos +:= 1
OD;
IF current count > max count THEN
max count := current count;
modes[ mode count := 1 ] := sorted data[ s pos - 1 ]
ELIF current count = max count THEN
modes[ mode count +:= 1 ] := sorted data[ s pos - 1 ]
FI;
current count := 0;
IF s pos <= UPB sorted data THEN
current value := sorted data[ s pos ]
FI
OD;
modes[ 1 : mode count ]
FI # MODEOF # ;
 
# test cases as in the 11l sample #
=={{Header|AutoHotkey}}==
SHOW MODEOF []INT( 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17 );print( ( newline ) );
SHOW MODEOF []INT( 1, 1, 2, 4, 4 ) ;print( ( newline ) );
# test cases as in the Action! sample #
SHOW MODEOF []INT( 1, 3, 5, 7, 3, 1, 3, 7, 7, 3, 3 ) ;print( ( newline ) );
SHOW MODEOF []INT( 7, 13, 5, 13, 7, 2, 7, 10, 13 ) ;print( ( newline ) );
SHOW MODEOF []INT( 5 ) ;print( ( newline ) );
# additional test case #
SHOW MODEOF []INT( 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 ) ;print( ( newline )
 
END
</syntaxhighlight>
{{out}}
<pre>
6
1 4
3
7 13
5
9
</pre>
 
=={{header|APL}}==
<syntaxhighlight lang="apl">mode←{{s←⌈/⍵[;2]⋄⊃¨(↓⍵)∩{⍵,s}¨⍵[;1]}{⍺,≢⍵}⌸⍵}</syntaxhighlight>
 
=={{header|AppleScript}}==
 
This works with both lists and records containing numbers and/or text values.
 
<syntaxhighlight lang="applescript">use AppleScript version "2.3.1" -- Mac OS X 10.9 (Mavericks) or later (for these 'use' commands).
use sorter : script "Shell sort" -- https://www.rosettacode.org/wiki/Sorting_algorithms/Shell_sort#AppleScript
 
on modeOf(listOrRecord)
-- Extract and sort numbers and text separately, then concatenate the results to get a single list of values.
set theNumbers to listOrRecord's numbers
tell sorter to sort(theNumbers, 1, -1)
set theTexts to listOrRecord's text
tell sorter to sort(theTexts, 1, -1)
script o
property values : theNumbers & theTexts
property mode : {}
end script
-- Identify the most frequently occurring value(s).
if (o's values is not {}) then
set i to 1
set currentValue to beginning of o's values
set maxCount to 1
repeat with j from 2 to (count o's values)
set thisValue to item j of o's values
if (thisValue is not currentValue) then
set thisCount to j - i
if (thisCount > maxCount) then
set o's mode to {currentValue}
set maxCount to thisCount
else if (thisCount = maxCount) then
set end of o's mode to currentValue
end if
set i to j
set currentValue to thisValue
end if
end repeat
if (j + 1 - i > maxCount) then
set o's mode to {currentValue}
else if (j + 1 - i = maxCount) then
set end of o's mode to currentValue
end if
end if
return o's mode
end modeOf
 
-- Test code:
-- With a list:
modeOf({12, 4, "rhubarb", 88, "rhubarb", 17, "custard", 4.0, 4, 88, "rhubarb"})
--> {4, "rhubarb"}
 
-- With a record:
modeOf({a:12, b:4, c:"rhubarb", d:88, e:"rhubarb", f:17, g:"custard", h:4.0, i:4, j:88})
--> {4}</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">getMode: function [arr][
freqs: new #[]
loop arr 'i [
k: to :string i
if not? key? freqs k -> set freqs k 0
freqs\[k]: (freqs\[k]) + 1
]
maximum: max values freqs
select keys freqs 'i -> maximum = freqs\[i]
]
print getMode [1 3 6 6 6 6 7 7 12 12 17]
print getMode [1 1 2 4 4]</syntaxhighlight>
 
{{out}}
 
<pre>6
1 4</pre>
 
=={{header|AutoHotkey}}==
{{AutoHotkey case}}
Source: [http://www.autohotkey.com/forum/post-276175.html#276175 AutoHotkey forum] by Laszlo
<langsyntaxhighlight lang="autohotkey">MsgBox % Mode("1 2 3")
MsgBox % Mode("1 2 0 3 0.0")
MsgBox % Mode("0.1 2.2 -0.1 0.22e1 2.20 0.1")
Line 211 ⟶ 492:
Else Ct++
Return Ct>MxCt ? V : MxV
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk">#!/usr/bin/gawk -f
{
# compute histogram
Line 244 ⟶ 525:
END {
print mode(histo);
};</langsyntaxhighlight>
 
<pre>cat modedata.txt
Line 264 ⟶ 545:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> DIM a(10), b(4)
a() = 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17
b() = 1, 2, 4, 4, 1
Line 297 ⟶ 578:
NEXT
= J%
</syntaxhighlight>
</lang>
{{out}}
<pre>Mode(s) of a() = 6
Mode(s) of b() = 1 4</pre>
 
=={{header|BQN}}==
 
[https://mlochbaum.github.io/bqncrate/?q=mode# BQNcrate] lists two functions for mode. Of these, the first is faster.
 
<pre>Mode1 ← ⌈´⊸=∘⊒⊸/
Mode2 ← ⊏∘⊑˘·(⌈´⊸=≠¨)⊸/⊐⊸⊔
 
arr ← 1‿1‿1‿1‿2‿2‿2‿3‿3‿3‿3‿4‿4‿3‿2‿4‿4‿4‿5‿5‿5‿5‿5
•Show Mode1 arr
•Show Mode2 arr</pre>
<pre>⟨ 3 4 5 ⟩
⟨ 3 4 5 ⟩</pre>
 
=={{header|C}}==
Using an array of doubles. If another data type is desired, the <code>cmp_dbl</code> and <code>vcount</code> definitions should be changed accordingly.
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 362 ⟶ 656:
free(vc);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>got 2 modes:
value = 6, count = 4
value = 12, count = 4</pre>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
 
namespace Test
{
class Program
{
static void Main(string[] args)
{
/*
* We Use Linq To Determine The Mode
*/
List<int> myList = new List<int>() { 1, 1, 2, 4, 4 };
 
var query = from numbers in myList //select the numbers
group numbers by numbers //group them together so we can get the count
into groupedNumbers
select new { Number = groupedNumbers.Key, Count = groupedNumbers.Count() }; //so we got a query
//find the max of the occurence of the mode
int max = query.Max(g => g.Count);
IEnumerable<int> modes = query.Where(x => x.Count == max).Select(x => x.Number);//match the frequence and select the number
foreach (var item in modes)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
 
}
}
</syntaxhighlight>
 
=={{header|C++}}==
{{works with|g++|4.3.2}}
<langsyntaxhighlight lang="cpp">#include <iterator>
#include <utility>
#include <algorithm>
Line 437 ⟶ 772:
std::cout << std::endl;
return 0;
}</langsyntaxhighlight>
{{out}}
2 3
 
=={{header|C sharp|C#}}==
<lang csharp>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
 
namespace Test
{
class Program
{
static void Main(string[] args)
{
/*
* We Use Linq To Determine The Mode
*/
List<int> myList = new List<int>() { 1, 1, 2, 4, 4 };
 
var query = from numbers in myList //select the numbers
group numbers by numbers //group them together so we can get the count
into groupedNumbers
select new { Number = groupedNumbers.Key, Count = groupedNumbers.Count() }; //so we got a query
//find the max of the occurence of the mode
int max = query.Max(g => g.Count);
IEnumerable<int> modes = query.Where(x => x.Count == max).Select(x => x.Number);//match the frequence and select the number
foreach (var item in modes)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
 
}
}
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn modes [coll]
(let [distrib (frequencies coll)
[value freq] [first second] ; name the key/value pairs in the distrib (map) entries
sorted (sort-by (comp - freq) distrib)
maxfq (freq (first sorted))]
(map value (take-while #(= maxfq (freq %)) sorted))))</langsyntaxhighlight>
Or a one-liner solution
<syntaxhighlight lang="clojure">(defn modes [coll]
(->> coll frequencies (sort-by val >) (partition-by val) first (map key)))</syntaxhighlight>
 
== {{header|CoffeeScript}} ==
<langsyntaxhighlight lang="coffeescript">mode = (arr) ->
# returns an array with the modes of arr, i.e. the
# elements that appear most often in arr
Line 503 ⟶ 800:
(key for key, cnt of counts when cnt == max)
console.log mode [1, 2, 2, 2, 3, 3, 3, 4, 4]</langsyntaxhighlight>
 
== {{header|Common Lisp}} ==
The following returns a list of the modes of a sequence as the primary value, and the frequency as the secondary value. E.g., <code>(mode '(a b c d a b c a b))</code> produces <code>(A B)</code> and <code>3</code>. hash-table-options can be used to customize the hash table, e.g., to specify the test by which elements are compared.
<langsyntaxhighlight lang="lisp">(defun mode (sequence &rest hash-table-options)
(let ((frequencies (apply #'make-hash-table hash-table-options)))
(map nil (lambda (element)
Line 521 ⟶ 818:
(push element modes))))
frequencies)
(values modes hifreq))))</langsyntaxhighlight>
 
=={{header|D}}==
The mode function returns a range of all the mode items:
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.array;
 
auto mode(T)(T[] items) pure /*nothrow @safe*/ {
Line 541 ⟶ 838:
data ~= 2;
writeln("Mode: ", data.mode);
}</langsyntaxhighlight>
{{out}}
<pre>Mode: [3]
Mode: [2, 3]</pre>
=={{header|Delphi}}==
{{libheader| System.Generics.Collections}}
{{libheader| System.Generics.Defaults}}
<syntaxhighlight lang="delphi">
program AveragesMode;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
System.Generics.Collections,
System.Generics.Defaults;
 
type
TCounts = TDictionary<Integer, Integer>;
 
TPair = record
value, count: Integer;
constructor Create(value, count: Integer);
end;
 
TPairs = TArray<TPair>;
 
var
dict: TCounts;
Pairs: TPairs;
list: TArray<Integer>;
i, key, max: Integer;
p: TPair;
 
{ TPair }
 
constructor TPair.Create(value, count: Integer);
begin
self.value := value;
self.count := count;
end;
 
function SortByCount(const left, right: TPair): Integer;
begin
Result := right.count - left.count;
end;
 
begin
list := [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 12, 12, 17];
dict := TCounts.Create;
 
for i in list do
begin
if dict.ContainsKey(i) then
dict[i] := dict[i] + 1
else
begin
dict.Add(i, 1);
end;
end;
 
SetLength(Pairs, dict.Count);
i := 0;
for key in dict.Keys do
begin
Pairs[i] := TPair.Create(key, dict[key]);
inc(i);
end;
 
TArray.Sort<TPair>(Pairs, TComparer<TPair>.Construct(SortByCount));
 
Writeln('Modes:');
max := Pairs[0].count;
for p in Pairs do
if p.count = max then
Writeln(' Value: ', p.value, ', Count: ', p.count);
 
dict.Free;
Readln;
end.</syntaxhighlight>
{{out}}
<pre>Modes:
Value: 6, Count: 4
Value: 12, Count: 4</pre>
=={{header|E}}==
<langsyntaxhighlight lang="e">pragma.enable("accumulator")
def mode(values) {
def counts := [].asMap().diverge()
Line 555 ⟶ 931:
}
return accum [].asSet() for v => ==maxCount in counts { _.with(v) }
}</langsyntaxhighlight>
<langsyntaxhighlight lang="e">? mode([1,1,2,2,3,3,4,4,4,5,5,6,6,7,8,8,9,9,0,0,0])
# value: [4, 0].asSet()</langsyntaxhighlight>
In the line "<code>maxCount max= (counts[v] := counts.fetch(v, fn{0}) + 1)</code>", <code>max=</code> is an update-assignment operation like <code>+=</code>. (The parentheses are unnecessary.) A more verbose version would be:
<langsyntaxhighlight lang="e"> def newCount := counts.fetch(v, fn { 0 }) + 1
counts[v] := newCount
maxCount := maxCount.max(newCount)</langsyntaxhighlight>
In for loops, each key and value from the collection are [[Pattern Matching|pattern matched]] against the specified <code><var>key pattern</var> => <var>value pattern</var></code>. In "<code>for v => ==maxCount in counts</code>", the <code>==</code> is a pattern-match operator which fails unless the value examined is equal to the specified value; so this selects only the input values (keys in <code>counts</code>) whose counts are equal to the maximum count.
 
=={{header|EasyLang}}==
<syntaxhighlight>
proc modes . in[] r[] .
r[] = [ ]
for v in in[]
for i to len vals[]
if v = vals[i]
cnt[i] += 1
max = higher cnt[i] max
break 1
.
.
vals[] &= v
cnt[] &= 0
.
for i to len cnt[]
if cnt[i] = max
r[] &= vals[i]
.
.
.
in[] = [ 1 3 6 6 6 6 7 7 12 12 17 ]
modes in[] mods[]
print mods[]
in[] = [ 1 1 2 4 4 ]
modes in[] mods[]
print mods[]
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(define (modes L)
(define G (group* L)) ;; sorts and group equal items
Line 582 ⟶ 987:
(modes '())
😖️ error: group : expected list : null 🔎 'modes'
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 36.4x:
<langsyntaxhighlight lang="elena">import system'routines.;
import system'collections.;
import extensions.;
 
extension op
{
modeget Mode()
[{
var aCountMapcountMap := Dictionary .new(0).;
self .forEach(:anItem:(item)
[{
aCountMapcountMap[anItemitem] := aCountMapcountMap[anItemitem] + 1
].};
aCountMapcountMap := aCountMap values; countMap.Values.sort(:p:n)(p,n => p > n).;
var aMaxmax := aCountMap firstMembercountMap.FirstMember;
^ aCountMapcountMap
.filterBy::(:kv)(aMax => max.equal(kv value.Value));
.selectBy(:kv):(kv key=> kv.Key);
toArray.toArray()
]}
}
 
public program()
{
[
var anArray1array1 := (new int[]{1, 1, 2, 4, 4).};
var anArray2array2 := (new int[]{1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17).};
var anArray3array3 := (new object[]{1, "blue", 2, 7.5r, 5, "green", "red", 5, 2, "blue", "white").};
console
.printLine("mode of (",anArray1array1.asEnumerable(),") is (",anArray1 modearray1.Mode,")");
.printLine("mode of (",anArray2array2.asEnumerable(),") is (",anArray2 modearray2.Mode,")");
.printLine("mode of (",anArray3array3.asEnumerable(),") is (",anArray3 modearray3.Mode,")");
readChar.readChar()
}</syntaxhighlight>
]</lang>
{{out}}
<pre>
Line 631 ⟶ 1,036:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Average do
def mode(list) do
gb = Enum.group_by(list, &(&1))
Line 644 ⟶ 1,049:
IO.puts "mode: #{inspect list}"
IO.puts " => #{inspect Average.mode(list)}"
end)</langsyntaxhighlight>
 
{{out}}
Line 655 ⟶ 1,060:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( mode ).
-export( [example/0, values/1] ).
Line 677 ⟶ 1,082:
 
values_count( Value, Dict ) -> dict:update_counter( Value, 1, Dict ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 685 ⟶ 1,090:
 
=={{header|ERRE}}==
<langsyntaxhighlight ERRElang="erre">PROGRAM MODE_AVG
 
!$INTEGER
Line 745 ⟶ 1,150:
CALC_MODE(B[],4->MODES$)
PRINT(MODES$)
END PROGRAM</langsyntaxhighlight>
{{out}}
<pre>
Line 751 ⟶ 1,156:
Modes for array B (1,2,4,4,1) 1 4
</pre>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">include misc.e
 
function mode(sequence s)
Line 790 ⟶ 1,196:
 
constant s = { 1, "blue", 2, 7.5, 5, "green", "red", 5, 2, "blue", "white" }
pretty_print(1,mode(s),{3})</langsyntaxhighlight>
{{out}}
<pre>{
Line 800 ⟶ 1,206:
=={{header|F_Sharp|F#}}==
The Unchecked.defaultof became available in version 1.9.4 I think.
<langsyntaxhighlight lang="fsharp">let mode (l:'a seq) =
l
|> Seq.countBy (fun item -> item) // Count individual items
Line 809 ⟶ 1,215:
else (cp,lst)) // else just keep old count/list
(0, [Unchecked.defaultof<'a>]) // Start with a count of 0 and a dummy item
|> snd // From (count, list) we just want the second item (the list)</langsyntaxhighlight>
Example usage:
<langsyntaxhighlight lang="fsharp">> mode ["a"; "b"; "c"; "c"];;
val it : string list = ["c"]
> mode ["a"; "b"; "c"; "c";"a"];;
val it : string list = ["c"; "a"]
> mode [1;2;1;3;2;0;0];;
val it : int list = [0; 2; 1]</langsyntaxhighlight>
 
=={{header|Factor}}==
Factor has the word <code>mode</code> in <code>math.statistics</code> vocabulary.
<langsyntaxhighlight lang="factor">{ 11 9 4 9 4 9 } mode ! 9 </langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
For the <tt>Qsort_Module</tt> see [[Sorting_algorithms/Quicksort#Fortran]]
<langsyntaxhighlight lang="fortran">program mode_test
use Qsort_Module only Qsort => sort
implicit none
Line 922 ⟶ 1,328:
end function stat_mode
 
end program mode_test</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub quicksort(a() As Integer, first As Integer, last As Integer)
Line 990 ⟶ 1,396:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 999 ⟶ 1,405:
</pre>
 
=={{header|HaskellFrink}}==
<syntaxhighlight lang="frink">modes[vals] :=
<lang haskell>import Prelude (foldr, maximum, (==), (+))
{
import Data.Map (insertWith', empty, filter, elems, keys)
count = countToArray[vals]
biggest = count@0@1
result = new array
for i = rangeOf[count]
if count@i@1 < biggest
break // count is sorted so we can bail out when numbers decrease
else
result.push[count@i@0]
 
return result
mode :: (Ord a) => [a] -> [a]
}
mode xs = keys (filter (== maximum (elems counts)) counts)
where counts = foldr (\x -> insertWith' (+) x 1) empty xs</lang>
''counts'' is a map from each value found in ''xs'' to the number of occurrences (foldr traverses the list, insertWith' increments the count). This map is then filtered to only those entries whose count is the maximum count, and their keys (the values from the input list) are returned.
> mode [1,2,3,3,2,1,1]
[1]
> mode [1,2,3,3,2,1]
[1,2,3]
Alternately:
<lang haskell>import Data.List (group, sort)
 
println[modes[[1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]]]
mode :: (Ord a) => [a] -> [a]
println[modes[[1, 1, 2, 4, 4]]]</syntaxhighlight>
mode xs = map fst $ filter ((==best).snd) counts
{{out}}
where counts = map (\l -> (head l, length l)) . group . sort $ xs
<pre>
best = maximum (map snd counts)</lang>
[6]
Another version that does not require an orderable type:
[1, 4]
<lang haskell>import Data.List (partition)
</pre>
As of the 2022-07-31 release of Frink, the function can be rewritten as:
<syntaxhighlight lang="frink">modes[vals] := mostCommon[vals]@0</syntaxhighlight>
 
=={{header|FutureBasic}}==
FB has a native function for an array of mode averages.
<syntaxhighlight lang="futurebasic">
local fn ModeAverage( arguments as CFArrayRef ) as CFStringRef
ExpressionRef expRef = fn ExpressionForFunction( @"mode:", @[fn ExpressionForConstantValue( arguments )] )
CFArrayRef modeArray = fn ExpressionValueWithObject( expRef, NULL, NULL )
CFNumberRef number
CFMutableStringRef modeStr = fn MutableStringNew
for number in modeArray
MutableStringAppendFormat( modeStr, @"value = %@\n", number )
next
end fn = modeStr
 
print fn ModeAverage( @[@1, @3, @6, @6, @6, @6, @7, @7, @12, @12, @12, @12, @17] )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
value = 6
value = 12
</pre>
 
mode :: (Eq a) => [a] -> [a]
mode = snd . modesWithCount
where modesWithCount :: (Eq a) => [a] -> (Int, [a])
modesWithCount [] = (0,[])
modesWithCount l@(x:_) | length xs > best = (length xs, [x])
| length xs < best = (best, modes)
| otherwise = (best, x:modes)
where (xs, notxs) = partition (== x) l
(best, modes) = modesWithCount notxs</lang>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">mode := function(v)
local c, m;
c := Collected(SortedList(v));
Line 1,040 ⟶ 1,464:
 
mode([ 7, 5, 6, 1, 5, 5, 7, 12, 17, 6, 6, 5, 12, 3, 6 ]);
# [ 5, 6 ]</langsyntaxhighlight>
 
=={{header|Go}}==
'''Fixed collection type, fixed value type.''' In Go it is appropriate to program directly with built in types when possible.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,071 ⟶ 1,495:
}
return mode
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,078 ⟶ 1,502:
</pre>
'''Fixed collection type, unspecified value type.''' An empty interface can hold any type. A slice <tt>[]interface</tt> can hold a mix of types. It's not too much more source code, although there is some overhead to support this generality.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,105 ⟶ 1,529:
}
return mode
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,112 ⟶ 1,536:
</pre>
'''General collection, fixed value type.''' The other kind of generality mentioned in the task requires more code. In Go this is done with an interface to define generalized collection methods. Here, the only method we need to demonstrate is iteration over the collection, so the interface has only one method. Any number of types then can implement the interface. Note that the mode function now takes an object of this interface type. In effect, it becomes a generic function, oblivious to the implementation of the collection, and accessing it only through its methods.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,168 ⟶ 1,592:
}
return mode
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,175 ⟶ 1,599:
</pre>
'''General collection, unspecified value type,''' Finally, the two kinds of generality can be combined. The iterator returned by the interface method now returns an empty interface rather than an int. The intSlice concrete type of the previous example is retained, but now it must satisfy this interface method that uses <tt>interface{}</tt> instead of int. <tt>runeList</tt> is added to illustrate how multiple types can satisfy the same interface.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,241 ⟶ 1,665:
}
return mode
}</langsyntaxhighlight>
{{out}}
("Enzyklopädie" has no repeated letters. All are modal.)
Line 1,251 ⟶ 1,675:
=={{header|Groovy}}==
Solution, both "collection type" and "element type" agnostic:
<langsyntaxhighlight lang="groovy">def mode(Iterable col) {
assert col
def m = [:]
Line 1,259 ⟶ 1,683:
def keys = m.keySet().sort { -m[it] }
keys.findAll { m[it] == m[keys[0]] }
}</langsyntaxhighlight>
Test:
<langsyntaxhighlight lang="groovy">def random = new Random()
def sourceList = [ 'Lamp', 42.0, java.awt.Color.RED, new Date(), ~/pattern/]
(0..10).each {
def a = (0..10).collect { sourceList[random.nextInt(5)] }
println "${mode(a)} == mode(${a})"
}</langsyntaxhighlight>
{{out}}
<pre>[pattern] == mode([pattern, pattern, pattern, Lamp, pattern, Fri Oct 28 23:43:20 CDT 2011, java.awt.Color[r=255,g=0,b=0], Lamp, Lamp, Lamp, pattern])
Line 1,279 ⟶ 1,703:
[pattern] == mode([42.0, pattern, pattern, Lamp, 42.0, Lamp, Fri Oct 28 23:43:20 CDT 2011, java.awt.Color[r=255,g=0,b=0], pattern, 42.0, pattern])
[Lamp, 42.0] == mode([Fri Oct 28 23:43:20 CDT 2011, pattern, Lamp, Lamp, Lamp, java.awt.Color[r=255,g=0,b=0], Fri Oct 28 23:43:20 CDT 2011, 42.0, 42.0, pattern, 42.0])</pre>
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">import Prelude (foldr, maximum, (==), (+))
import Data.Map (insertWith', empty, filter, elems, keys)
 
mode :: (Ord a) => [a] -> [a]
mode xs = keys (filter (== maximum (elems counts)) counts)
where counts = foldr (\x -> insertWith' (+) x 1) empty xs</syntaxhighlight>
''counts'' is a map from each value found in ''xs'' to the number of occurrences (foldr traverses the list, insertWith' increments the count). This map is then filtered to only those entries whose count is the maximum count, and their keys (the values from the input list) are returned.
> mode [1,2,3,3,2,1,1]
[1]
> mode [1,2,3,3,2,1]
[1,2,3]
Alternately:
<syntaxhighlight lang="haskell">import Data.List (group, sort)
 
mode :: (Ord a) => [a] -> [a]
mode xs = map fst $ filter ((==best).snd) counts
where counts = map (\l -> (head l, length l)) . group . sort $ xs
best = maximum (map snd counts)</syntaxhighlight>
Another version that does not require an orderable type:
<syntaxhighlight lang="haskell">import Data.List (partition)
 
mode :: (Eq a) => [a] -> [a]
mode = snd . modesWithCount
where modesWithCount :: (Eq a) => [a] -> (Int, [a])
modesWithCount [] = (0,[])
modesWithCount l@(x:_) | length xs > best = (length xs, [x])
| length xs < best = (best, modes)
| otherwise = (best, x:modes)
where (xs, notxs) = partition (== x) l
(best, modes) = modesWithCount notxs</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
The <tt>mode</tt> procedure generates all <i>n</i> mode values if the collection is <i>n</i>-modal.
<langsyntaxhighlight lang="icon">procedure main(args)
every write(!mode(args))
end
Line 1,295 ⟶ 1,751:
else fail
}
end</langsyntaxhighlight>
{{out|Sample outputs}}
<pre>->am 3 1 4 1 5 9 7 6
Line 1,305 ⟶ 1,761:
 
=={{header|J}}==
<langsyntaxhighlight lang="j">mode=: ~. #~ ( = >./ )@( #/.~ )</langsyntaxhighlight>
 
Literally: select from the unique values the values which appear the most often.
 
Example:
<pre> mode 1 1 2 2 3 3 4 4 4 5 5 6 6 7 8 8 9 9 0 0 0
4 0</pre>
mode 1 3 6 6 6 6 7 7 12 12 17
6
mode 1 2 4 4 1
1 4
</pre>
 
=={{header|Jakt}}==
An empty set is returned if the iterable is empty.
 
<syntaxhighlight lang="jakt">
fn mode<T, U>(anon iterable: U) throws -> {T} {
mut dictionary = Dictionary<T, u64>()
for item in iterable {
if dictionary.contains(item) {
dictionary[item]++
} else {
dictionary[item] = 1
}
}
 
mut items = dictionary.iterator()
 
let mode = items.next()
if not mode.has_value() {
let empty_set: {T} = {}
return empty_set
}
 
mut modes = [mode.value()]
for item in items {
if item.1 > modes[0].1 {
modes = [item]
} else if item.1 == modes[0].1 {
modes.push(item)
}
}
 
mut mode_set: {T} = {}
for mode in modes {
mode_set.add(mode.0)
}
 
return mode_set
}
 
fn main() {
println("{}", mode<i64>([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]))
println("{}", mode<i64>([1, 1, 2, 4, 4]))
 
let empty_array: [i64] = []
println("{}", mode<i64>(empty_array))
 
let test_string = "abcabbcaca"
println("{}", mode<u32>(test_string.code_points()))
}
</syntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.*;
 
public class Mode {
Line 1,338 ⟶ 1,853:
System.out.println(mode(Arrays.asList(1, 1, 2, 4, 4))); // prints [1, 4]
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">function mode(ary) {
var counter = {};
var mode = [];
Line 1,361 ⟶ 1,876:
 
mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]); // [6]
mode([1, 2, 4, 4, 1]); // [1,4]</langsyntaxhighlight>
 
=={{header|jq}}==
jq only supports hashing of strings, so to preserve generality -- that is, to avoid assuming anything about the input array -- we simply sort it.
jq's <tt>sort</tt> is very fast in any case.<langsyntaxhighlight lang="jq"># modes/0 produces an array of [value, count]
# in increasing order of count:
def modes:
Line 1,383 ⟶ 1,898:
| $modes[-1][1] as $count
| $modes[] | select( .[1] == $count) | .[0]
end;</langsyntaxhighlight>Examples:<syntaxhighlight lang ="jq">
[1,2,3,1,2,1] | mode # => 1
[1,2,3,1,2,1,2] | mode # => 1 2
[1.1, 1.2, 1.3, 1.1, 1.2, 1.1] | mode) # => 1.1</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight klang="julia">function modes(values)
dict = Dict() # Values => Number of repetitions
modesArray = typeof(values[1])[] # Array of the modes so far
Line 1,417 ⟶ 1,932:
 
println(modes([1,3,6,6,6,6,7,7,12,12,17]))
println(modes((1,1,2,4,4)))</langsyntaxhighlight>
 
=={{header|K}}==
<langsyntaxhighlight lang="k"> mode: {(?x)@&n=|/n:#:'=x}
mode 1 1 1 1 2 2 2 3 3 3 3 4 4 3 2 4 4 4
3 4</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">fun <T> modeOf(a: Array<T>) {
val sortedByFreq = a.groupBy { it }.entries.sortedByDescending { it.value.size }
val maxFreq = sortedByFreq.first().value.size
Line 1,445 ⟶ 1,960:
println("[" + b.joinToString(", ") + "]")
modeOf(b)
}</langsyntaxhighlight>
 
{{out}}
Line 1,457 ⟶ 1,972:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define getmode(a::array)::array => {
local(mmap = map, maxv = 0, modes = array)
// store counts
Line 1,468 ⟶ 1,983:
}
getmode(array(1,3,6,6,6,6,7,7,12,12,17))
getmode(array(1,3,6,3,4,8,9,1,2,3,2,2))</langsyntaxhighlight>
 
{{out}}
Line 1,476 ⟶ 1,991:
=={{header|Liberty BASIC}}==
Using string of integers instead collection.
<syntaxhighlight lang="lb">
<lang lb>
a$ = "1 3 6 6 6 6 7 7 12 12 17"
b$ = "1 2 4 4 1"
Line 1,534 ⟶ 2,049:
modes$ = modes$; oldVal; " "
end select
end function </langsyntaxhighlight>
 
{{out}}
Line 1,545 ⟶ 2,060:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function mode(tbl) -- returns table of modes and count
assert(type(tbl) == 'table')
local counts = { }
Line 1,572 ⟶ 2,087:
for _, val in pairs(modes) do io.write(val..' ') end
print("occur(s) ", count, " times")
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
Line 1,579 ⟶ 2,094:
Function return an inventory, with all "modes" with same max number. Now work with mix numbers and strings. Islet return true if top of stack is letter (string).
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
\\ find mode
Line 1,624 ⟶ 2,139:
}
Checkit
</syntaxhighlight>
</lang>
 
Using idea from BBC BASIC. Function GetMode return array. As Array get bigger function run slower exponential. Previous example using inventory, has linear response (double data, double time to run). Eacb function has a mew stack of value. This one line function Def AllStack()=[] get all arguments and place them in a stack object, and a pointer to stack returned. This function return an array: Def AllArray=Array([]). We can use (,) for empty array, (1,) for one item array, (1,2,3) for three item. We can use ((1,2),(3,4)) for an array with two arrays as items. We can use Stack for empty stack, or Stack:=1,2,3 for a stack with 3 items. Stacks are linked lists. A=Stack : Stack A { push 1,2,3 } : Print A ' print 3 2 1 where 3 is the top. Stack A (Data 0} : Print A ' print 3 2 1 0 (data push to bottom to stack). Functions and Modules always have a "current stack". So M2000 is like basic but is a stack oriented language, but for expressions use infix notation.
Line 1,630 ⟶ 2,145:
 
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Function GetMode(&a()){
Line 1,677 ⟶ 2,192:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
The built-in function Statistics:-Mode can be used to compute a mode.
When the mode is unique, it returns a numeric result and when there are multiple modes, it returns a set, as in the following example:
<langsyntaxhighlight Maplelang="maple">Statistics:-Mode([1, 2.1, 2.1, 3]);
Statistics:-Mode([1, 2.1, 2.1, 3.2, 3.2, 5]);</langsyntaxhighlight>
 
{{out}}
Line 1,692 ⟶ 2,207:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Built-in function commonest returns a '''list''' of the most common element(s), even is there is only one 'commonest' number. Example for multiple 'commonest' numbers and a single 'commonest' number:
<langsyntaxhighlight Mathematicalang="mathematica"> Commonest[{b, a, c, 2, a, b, 1, 2, 3}]
Commonest[{1, 3, 2, 3}]</langsyntaxhighlight>
{{out}}
<pre> {b,a,2}
Line 1,699 ⟶ 2,214:
 
=={{header|MATLAB}}==
<langsyntaxhighlight Matlablang="matlab">function modeValue = findmode(setOfValues)
modeValue = mode(setOfValues);
end</langsyntaxhighlight>
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">MODE(X)
;X is assumed to be a list of numbers separated by "^"
;I is a loop index
Line 1,718 ⟶ 2,233:
SET I="",I=$O(Y(I)),ML=I ;Prime the pump, rather than test for no data
FOR S I=$O(Y(I)) Q:I="" S ML=$SELECT(Y($P(ML,"^"))>Y(I):ML,Y($P(ML,"^"))<Y(I):I,Y($P(ML,"^"))=Y(I):ML_"^"_I)
QUIT ML</langsyntaxhighlight>
<pre>USER>W $$MODE^ROSETTA("1^2^3^2")
2
Line 1,727 ⟶ 2,242:
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,802 ⟶ 2,317:
show_mode([Rexx 1, 1, 2, 4, 4]) -- 4 1
return
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 1,825 ⟶ 2,340:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import tables
 
proc modes[T](xs: openArray[T]): T =
Line 1,834 ⟶ 2,349:
 
echo modes(@[1,3,6,6,6,6,7,7,12,12,17])
echo modes(@[1,1,2,4,4])</langsyntaxhighlight>
Output:
<pre>6
1</pre>
 
=={{header|Oberon-2}}==
{{Works with|oo2c version2}}
<langsyntaxhighlight lang="oberon2">
MODULE Mode;
IMPORT
Line 1,917 ⟶ 2,433:
Show(Mode(z));Out.Ln;
END Mode.
</syntaxhighlight>
</lang>
{{out}
<pre>
Line 1,927 ⟶ 2,443:
5
</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
use Collection;
 
Line 1,979 ⟶ 2,496:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
@interface NSArray (Mode)
Line 2,005 ⟶ 2,522:
return maxElems;
}
@end</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let mode lst =
let seen = Hashtbl.create 42 in
List.iter (fun x ->
Line 2,020 ⟶ 2,537:
if v = best then k :: acc
else acc)
seen []</langsyntaxhighlight>
# mode [1;3;6;6;6;6;7;7;12;12;17];;
- : int list = [6]
Line 2,028 ⟶ 2,545:
=={{header|Octave}}==
Of course Octave has the <tt>mode</tt> function; but it returns only the "lowest" mode if multiple modes are available.
<langsyntaxhighlight lang="octave">function m = mode2(v)
sv = sort(v);
% build two vectors, vals and c, so that
Line 2,056 ⟶ 2,573:
i++;
endwhile
endfunction</langsyntaxhighlight>
<langsyntaxhighlight lang="octave">a = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
mode2(a)
mode(a)
Line 2,063 ⟶ 2,580:
a = [1, 1, 2, 4, 4];
mode2(a) % returns 1 and 4
mode(a) % returns 1 only</langsyntaxhighlight>
 
=={{header|ooRexx}}==
See the example at [[#Version_2|REXX, Version 2]] for a version that returns multiple mode values.
<syntaxhighlight lang="oorexx">
<lang ooRexx>
-- will work with just about any collection...
call testMode .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
Line 2,100 ⟶ 2,617:
 
return mode
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
fun {Mode Xs}
Freq = {Dictionary.new}
Line 2,119 ⟶ 2,636:
in
{Show {Mode [1 2 3 3 2 1 1]}}
{Show {Mode [1 2 3 3 2 1]}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">mode(v)={
my(count=1,r=1,b=v[1]);
v=vecsort(v);
Line 2,137 ⟶ 2,654:
);
if(count>r,v[#v],b)
};</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use List::Util qw(max);
 
Line 2,151 ⟶ 2,668:
my $best = max(values %c);
return grep { $c{$_} == $best } keys %c;
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="perl">print "$_ " foreach mode(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17);
print "\n";
print "$_ " foreach mode(1, 1, 2, 4, 4);
print "\n";</langsyntaxhighlight>
 
=={{header|Perl 6}}==
 
{{works with|Rakudo|2018.03}}
<lang perl6>sub mode (*@a) {
my %counts := @a.Bag;
my $max = %counts.values.max;
return |%counts.grep(*.value == $max).map(*.key);
}
 
# Testing with arrays:
say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
say mode [1, 1, 2, 4, 4];</lang>
 
{{out}}
<pre>
6
(4 1)
</pre>
 
Alternatively, a version that uses a single method chain with no temporary variables: (Same output with same input)
 
<lang perl6>sub mode (*@a) {
return |(@a
.Bag # count elements
.classify(*.value) # group elements with the same count
.max(*.key) # get group with the highest count
.value.map(*.key); # get elements in the group
);
}
 
say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
say mode [1, 1, 2, 4, 4];</lang>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function mode(sequence s)
<span style="color: #008080;">function</span> <span style="color: #000000;">mode</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
-- returns a list of the most common values, each of which occurs the same number of times
<span style="color: #000080;font-style:italic;">-- returns a list of the most common values, each of which occurs the same number of times</span>
object this
<span style="color: #004080;">integer</span> <span style="color: #000000;">nxt</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">maxc</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
integer nxt = 1, count = 1, maxc = 1
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
sequence res = {}
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
if length(s)!=0 then
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
s = sort(s)
<span style="color: #004080;">object</span> <span style="color: #000000;">prev</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
this = s[1]
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
for i=2 to length(s) do
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]!=</span><span style="color: #000000;">prev</span> <span style="color: #008080;">then</span>
if s[i]!=this then
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">nxt</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">count</span><span style="color: #0000FF;">,</span><span style="color: #000000;">prev</span><span style="color: #0000FF;">}</span>
s[nxt] = {count,this}
<span style="color: #000000;">nxt</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
nxt += 1
<span style="color: #000000;">prev</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
this = s[i]
<span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
count = 1
<span style="color: #008080;">else</span>
<span style="color: #000000;">count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
count += 1
<span style="color: #008080;">if</span> <span style="color: #000000;">count</span><span style="color: #0000FF;">></span><span style="color: #000000;">maxc</span> <span style="color: #008080;">then</span>
if count>maxc then
<span style="color: #000000;">maxc</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">count</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">nxt</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">count</span><span style="color: #0000FF;">,</span><span style="color: #000000;">prev</span><span style="color: #0000FF;">}</span>
s[nxt] = {count,this}
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
res = ""
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">nxt</span> <span style="color: #008080;">do</span>
for i=1 to nxt do
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">maxc</span> <span style="color: #008080;">then</span>
if s[i][1]=maxc then
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">2</span><span style="color: #0000FF;">])</span>
res = append(res,s[i][2])
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
return res
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
end function
<span style="color: #0000FF;">?</span><span style="color: #000000;">mode</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">9.5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3.14159</span><span style="color: #0000FF;">})</span>
?mode({1, 2, 5, -5, -9.5, 3.14159})
<span style="color: #0000FF;">?</span><span style="color: #000000;">mode</span><span style="color: #0000FF;">({</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"blue"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7.5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"green"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"red"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"blue"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"white"</span> <span style="color: #0000FF;">})</span>
?mode({ 1, "blue", 2, 7.5, 5, "green", "red", 5, 2, "blue", "white" })
<span style="color: #0000FF;">?</span><span style="color: #000000;">mode</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">})</span>
?mode({1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6})
<span style="color: #0000FF;">?</span><span style="color: #000000;">mode</span><span style="color: #0000FF;">({.</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">.</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">.</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">.</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">.</span><span style="color: #000000;">2</span><span style="color: #0000FF;">})</span>
?mode({.2, .7, .1, .8, .2})
<span style="color: #0000FF;">?</span><span style="color: #000000;">mode</span><span style="color: #0000FF;">({</span><span style="color: #008000;">"two"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"two"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">})</span>
?mode({"two", 7, 1, 8, "two", 8})
<span style="color: #0000FF;">?</span><span style="color: #000000;">mode</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Hello there world"</span><span style="color: #0000FF;">)</span>
?mode("Hello there world")
<span style="color: #0000FF;">?</span><span style="color: #000000;">mode</span><span style="color: #0000FF;">({})</span>
?mode({})
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
{} = wait_key()</lang>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,245 ⟶ 2,730:
=={{header|PHP}}==
Note: this function only works with strings and integers, as those are the only things that can be used as keys of an (associative) array in PHP.
<langsyntaxhighlight lang="php"><?php
function mode($arr) {
$count = array_count_values($arr);
Line 2,254 ⟶ 2,739:
print_r(mode(array(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17)));
print_r(mode(array(1, 1, 2, 4, 4)));
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de modes (Lst)
(let A NIL
(for X Lst
Line 2,263 ⟶ 2,748:
(mapcar car
(maxi cdar
(by cdr group A) ) ) ) )</langsyntaxhighlight>
{{out}}
<pre>: (modes (1 3 6 6 6 6 7 7 12 12 17))
Line 2,278 ⟶ 2,763:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">av: procedure options (main); /* 28 October 2013 */
declare x(10) fixed binary static initial (1, 4, 2, 6, 2, 5, 6, 2, 4, 2);
declare f(32767) fixed binary;
Line 2,297 ⟶ 2,782:
max || ' times.');
 
end av;</langsyntaxhighlight>
Results:
<pre>
Line 2,304 ⟶ 2,789:
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">$data = @(1,1,1,2,3,4,5,5,6,7,7,7)
$groups = $data | group-object | sort-object count -Descending
$groups | ? {$_.Count -eq $groups[0].Count}</langsyntaxhighlight>
{{out}}
<pre>Count Name Group
Line 2,314 ⟶ 2,799:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure mean(Array InArray(1))
 
Structure MyMean
Line 2,351 ⟶ 2,836:
EndIf
Next
EndProcedure</langsyntaxhighlight>
 
=={{header|Python}}==
The following solutions require that the elements be ''hashable''.
{{works with|Python|2.5+ and 3.x}}
<langsyntaxhighlight lang="python">>>> from collections import defaultdict
>>> def modes(values):
count = defaultdict(int)
Line 2,367 ⟶ 2,852:
[6]
>>> modes((1,1,2,4,4))
[1, 4]</langsyntaxhighlight>
{{works with|Python|2.7+ and 3.1+}}
<langsyntaxhighlight lang="python">>>> from collections import Counter
>>> def modes(values):
count = Counter(values)
Line 2,378 ⟶ 2,863:
[6]
>>> modes((1,1,2,4,4))
[1, 4]</langsyntaxhighlight>
If you just want one mode (instead of all of them), here's a one-liner for that:
<langsyntaxhighlight lang="python">def onemode(values):
return max(set(values), key=values.count)</langsyntaxhighlight>
 
=={{header|Q}}==
<syntaxhighlight lang="q">mode:{(key x) where value x=max x} count each group @</syntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ sort
[] [] rot
dup 0 peek temp put
witheach
[ dup temp share = iff
join
else
[ dup temp replace
dip [ nested join ]
[] join ] ]
nested join
temp release ] is bunch ( [ --> [ )
 
[ sortwith [ size dip size < ]
[] swap
dup 0 peek size temp put
witheach
[ dup size temp share = iff
[ nested join ]
else
[ drop conclude ] ]
temp release
[] swap
witheach
[ 0 peek join ] ] is largest ( [ --> [ )
 
 
[ bunch largest ] is mode ( [ --> [ )
 
' [ 1 3 5 7 3 1 3 7 7 3 3 ] mode echo cr
' [ 7 13 5 13 7 2 7 10 13 ] mode echo cr
' [ 5 ] mode echo cr</syntaxhighlight>
 
{{out}}
 
<pre>[ 3 ]
[ 7 13 ]
[ 5 ]
</pre>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">statmode <- function(v) {
a <- sort(table(v), decreasing=TRUE)
r <- c()
Line 2,397 ⟶ 2,927:
 
print(statmode(c(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17)))
print(statmode(c(1, 1, 2, 4, 4)))</langsyntaxhighlight>
 
=={{header|Racket}}==
Returns values of list of modes and their frequencies of appearance.
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(define (mode seq)
Line 2,418 ⟶ 2,948:
(values (cons k ms) freq)]
[else
(values ms freq)])))</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
 
{{works with|Rakudo|2019.03.1}}
<syntaxhighlight lang="raku" line>sub mode (*@a) {
my %counts := @a.Bag;
my $max = %counts.values.max;
%counts.grep(*.value == $max).map(*.key);
}
 
# Testing with arrays:
say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
say mode [1, 1, 2, 4, 4];</syntaxhighlight>
 
{{out}}
<pre>
6
(4 1)
</pre>
 
Alternatively, a version that uses a single method chain with no temporary variables: (Same output with same input)
 
<syntaxhighlight lang="raku" line>sub mode (*@a) {
@a.Bag # count elements
.classify(*.value) # group elements with the same count
.max(*.key) # get group with the highest count
.value.map(*.key); # get elements in the group
}
 
say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
say mode [1, 1, 2, 4, 4];</syntaxhighlight>
 
=={{header|REXX}}==
===version 1===
Returns one mode value.
<langsyntaxhighlight lang="rexx">/*REXX program finds the mode (most occurring element) of a vector. */
/* ════════vector═══════════ ═══show vector═══ ═════show result═════ */
v= 1 8 6 0 1 9 4 6 1 9 9 9 ; say 'vector='v; say 'mode='mode(v); say
Line 2,448 ⟶ 3,010:
end
end /*j*/
return ? /*return the mode of vector to invoker.*/</langsyntaxhighlight>
'''output'''
<pre>
Line 2,469 ⟶ 3,031:
{{works with|Regina}}
and should work for every REXX.
<langsyntaxhighlight REXXlang="rexx">/* Rexx */
/*-- ~~ main ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
call run_samples
Line 2,560 ⟶ 3,122:
call show_mode '1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17' -- 6
call show_mode '1, 1, 2, 4, 4' -- 4 1
return</langsyntaxhighlight>
{{out}}
<pre>Vector: [10,9,8,7,6,5,4,3,2,1], Mode(s): [10,9,8,7,6,5,4,3,2,1]
Line 2,581 ⟶ 3,143:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Averages/Mode
 
Line 2,624 ⟶ 3,186:
next
return j
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,631 ⟶ 3,193:
mode(s) of b() =
1 4
</pre>
 
=={{header|RPL}}==
∑VAL and ∑CNT are global lists used to store rep. values and counters.
Using the stack to handle potentially big amounts of data would slow down execution.
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
'''IF ∑VAL''' OVER POS
'''THEN '∑CNT'''' LAST ∑'''CNT''' OVER GET 1 + PUT DROP
'''ELSE ∑VAL''' SWAP + ''''∑VAL'''' STO '''∑CNT''' 1 + ''''∑CNT'''' STO '''END'''
≫ ''''∑ADD'''' STO
≪ → data
≪ { } DUP ''''∑VAL'''' STO ''''∑CNT'''' STO
1 data SIZE '''FOR''' j
data j GET '''∑ADD NEXT'''
'''∑CNT''' LIST→ { } + →ARRY RNRM { }
1 '''∑VAL''' SIZE '''FOR''' j
'''IF''' OVER ''''∑CNT'''' j GET ==
'''THEN '∑VAL'''' j GET
'''IF''' DUP2 POS NOT '''THEN''' + '''END'''
'''END NEXT'''
≫ ''''MODE'''' STO
|
'''∑ADD''' ''( n -- )'' // update ∑VAL and ∑CNT
if n already in ∑VAL
then increment corresponding position in ∑CNT
else create new in ∑VAL / ∑CNT entries
'''MODE''' ''( { data } -- { modal value(s) } )''
initialize ∑VAL and ∑CNT
for all input values
count occurrences
get max value in ∑CNT
for all distinct values
if count = max
then get value
and add it to output list if not already in
|}
 
{ 1 3 6 6 6 6 7 7 12 12 17 } '''MODE'''
{ 1 1 2 4 4 } '''MODE'''
{{out}}
<pre>
2: { 6 }
1: { 1 4 }
</pre>
 
=={{header|Ruby}}==
Here's two methods, the first more Ruby-ish, the second perhaps a bit more efficient.
<langsyntaxhighlight lang="ruby">def mode(ary)
seen = Hash.new(0)
ary.each {|value| seen[value] += 1}
Line 2,661 ⟶ 3,277:
p mode([1, 1, 2, 4, 4]) # => [1, 4]
p mode_one_pass([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]) # => [6]
p mode_one_pass([1, 1, 2, 4, 4]) # => [1, 4]</langsyntaxhighlight>
{{works with|Ruby|1.8.7}}
If you just want one mode (instead of all of them), here's a one-liner for that:
<langsyntaxhighlight lang="ruby">def one_mode(ary)
ary.max_by { |x| ary.count(x) }
end</langsyntaxhighlight>
 
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::collections::HashMap;
 
fn main() {
Line 2,701 ⟶ 3,316:
vec_mode
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,707 ⟶ 3,322:
Mode of vec2 is: [1,4] // may also print [4, 1], vector has no order guarantee
</pre>
 
 
=={{header|S-lang}}==
I'm accepting strings and numbers, although I'm converting numbers to strings,
as S-Lang Assoc_Type only accepts strings as keys.
<langsyntaxhighlight Slang="s-lang">private variable mx, mxkey, modedat;
 
define find_max(key) {
Line 2,750 ⟶ 3,364:
find_mode({"Hungadunga", "Hungadunga", "Hungadunga", "Hungadunga", "McCormick"});
 
find_mode({"foo", "2.3", "bar", "foo", "foobar", "quality", 2.3, "strnen"});</langsyntaxhighlight>
{{out}}
<pre>Hungadunga has the most entries (4).
Line 2,758 ⟶ 3,372:
{{works with|Scala|2.8}}
Receiving any collection is easy. Returning the result in the same collection takes some doing.
<langsyntaxhighlight lang="scala">import scala.collection.breakOut
import scala.collection.generic.CanBuildFrom
def mode
Line 2,767 ⟶ 3,381:
val max = grouped.map(_._2).max
grouped.filter(_._2 == max).map(_._1)(breakOut)
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
{{works with|Berkeley Scheme}}
<langsyntaxhighlight lang="scheme">(define (mode collection)
(define (helper collection counts)
(if (null? collection)
Line 2,780 ⟶ 3,394:
(map car
(filter (lambda (x) (= (cdr x) (apply max (map cdr (helper collection '())))))
(helper collection '())))</langsyntaxhighlight>
 
=={{header|Seed7}}==
Line 2,790 ⟶ 3,404:
This way the <code>main</code> function can just [http://seed7.sourceforge.net/libraries/enable_output.htm#write%28in_aType%29 write] the mode.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: createModeFunction (in type: elemType) is func
Line 2,840 ⟶ 3,454:
writeln(mode([] (1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17)));
writeln(mode([] (1, 1, 2, 4, 4)));
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,849 ⟶ 3,463:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func mode(array) {
var c = Hash.new;
array.each{|i| c{i} := 0 ++};
var max = c.values.max;
c.keys.grep{|i| c{i} == max};
}</langsyntaxhighlight>
 
'''Calling the function'''
<langsyntaxhighlight lang="ruby">say mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]).join(' ');
say mode([1, 1, 2, 4, 4]).join(' ');</langsyntaxhighlight>
 
{{out}}
Line 2,868 ⟶ 3,482:
If you just want one mode (instead of all of them), here's a one-liner for that:
 
<langsyntaxhighlight lang="ruby">func one_mode(arr) {
arr.max_by{|i| arr.count(i)};
}</langsyntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight Slatelang="slate">s@(Sequence traits) mode
[| sortedCounts |
sortedCounts: (s as: Bag) sortedCounts.
(sortedCounts mapSelect: [| :count :elem | sortedCounts last count = count]) valueSet
].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
This code is able to find the mode of any collection of any kind of object.
<langsyntaxhighlight lang="smalltalk">OrderedCollection extend [
mode [ |s|
s := self asBag sortedByCount.
Line 2,892 ⟶ 3,506:
mode displayNl.
#( 1 1 2 4 4) asOrderedCollection
mode displayNl.</langsyntaxhighlight>
 
=={{header|TclSQL}}==
Some databases have a built-in function. In Oracle you can say <code>select stats_mode(val) from...</code> but that returns one value, so doesn't handle non-unique modes. Other databases don't have a built-in. So here's a way to do this in a query.<syntaxhighlight lang="sql">-- setup
{{works with|Tcl|8.6}}
create table averages (val integer);
<lang tcl># Can find the modal value of any vector of values
insert into averages values (1);
proc mode {n args} {
insert into averages values (2);
foreach n [list $n {*}$args] {
insert into averages values (3);
dict incr counter $n
insert into averages values (1);
}
insert into averages values (2);
set counts [lsort -stride 2 -index 1 -decreasing $counter]
insert into averages values (4);
set best {}
insert into averages values (2);
foreach {n count} $counts {
insert into averages values (5);
if {[lindex $counts 1] == $count} {
insert into averages values (2);
lappend best $n
insert into averages values (3);
} else break
insert into averages values (3);
}
insert into averages values (1);
return $best
insert into averages values (3);
}
insert into averages values (6);
 
-- find the mode
# Testing
with
puts [mode 1 3 6 6 6 6 7 7 12 12 17]; # --> 6
counts as
puts [mode 1 1 2 4 4]; # --> 1 4</lang>
(
Note that this works for any kind of value.
select
val,
count(*) as num
from
averages
group by
val
)
select
val as mode_val
from
counts
where
num in (select max(num) from counts);</syntaxhighlight>
{{out}}
<pre> MODE_VAL
----------
2
3</pre>
 
=={{header|Swift}}==
Line 2,921 ⟶ 3,554:
This solution uses an extension of the Collection type to add a mode method. The only additional requirement of the Collection is that its Element conforms to Hashable.
 
<syntaxhighlight lang="swift">
<lang Swift>
// Extend the Collection protocol. Any type that conforms to extension where its Element type conforms to Hashable will automatically gain this method.
extension Collection where Element: Hashable {
Line 2,950 ⟶ 3,583:
emptyArray.mode() // returns nil
 
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<syntaxhighlight lang="tcl"># Can find the modal value of any vector of values
proc mode {n args} {
foreach n [list $n {*}$args] {
dict incr counter $n
}
set counts [lsort -stride 2 -index 1 -decreasing $counter]
set best {}
foreach {n count} $counts {
if {[lindex $counts 1] == $count} {
lappend best $n
} else break
}
return $best
}
 
# Testing
puts [mode 1 3 6 6 6 6 7 7 12 12 17]; # --> 6
puts [mode 1 1 2 4 4]; # --> 1 4</syntaxhighlight>
Note that this works for any kind of value.
 
=={{header|UNIX Shell}}==
{{works with|bash|4.0}}
<langsyntaxhighlight lang="bash">#!/bin/bash
 
function mode {
Line 2,968 ⟶ 3,623:
done
echo
}</langsyntaxhighlight>
<langsyntaxhighlight lang="bash">mode 1 2 1 2 a b a b a 2
a 2</langsyntaxhighlight>
 
=={{header|Ursala}}==
The mode function defined below works on lists of any type and returns a list of the modes. There is no concept of a general collection in Ursala. The algorithm is to partition the list by equality, then partition the classes by their lengths, and then select a representative from each member of the set of classes with the maximum length.
<langsyntaxhighlight Ursalalang="ursala">#import std
 
mode = ~&hS+ leql$^&h+ eql|=@K2
Line 2,980 ⟶ 3,635:
#cast %nLW
 
examples = mode~~ (<1,3,6,6,6,7,7,12,12,17>,<1,1,2,4,4>)</langsyntaxhighlight>
The function is tested on a pair of lists, one with a unique mode and one with multiple modes.
{{out}}
<pre>(<6>,<4,1>)</pre>
 
=={{header|VBA}}==
Using an array of integers to show the built-in Mode_Mult function, which find and displays the modes in an array. The function ignores text and only works for numbers.
<syntaxhighlight lang="vb">Public Sub main()
s = [{1,2,3,3,3,4,4,4,5,5,6}]
t = WorksheetFunction.Mode_Mult(s)
For Each x In t
Debug.Print x;
Next x
End Sub</syntaxhighlight>{{out}}
<pre> 3 4</pre>
 
=={{header|Vedit macro language}}==
Line 2,992 ⟶ 3,658:
The "mode" item and it's count are displayed on status line.
If there are multiple items with the same count, the smallest one is displayed.
<langsyntaxhighlight lang="vedit">BOF // Copy all data to a new buffer
Reg_Copy(10, ALL)
Buf_Switch(Buf_Free)
Line 3,016 ⟶ 3,682:
Reg_Copy_Block(10, CP, EOL_pos)
Buf_Quit(OK)
Statline_Message(@10)</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn main() {
println(mode([2, 7, 1, 8, 2]))
println(mode([2, 7, 1, 8, 2, 8]))
}
fn mode(a []int) []int {
mut m := map[int]int{}
for v in a {
m[v]++
}
mut mode := []int{}
mut n := 0
for k, v in m {
match true {
v > n {
n = v
mode = [k]
}
v<n{}
else {
mode << k
}
}
}
return mode
}</syntaxhighlight>
{{out}}
<pre>[2]
[2, 8]
</pre>
Or using `math.stats` module
<syntaxhighlight lang="vlang">import math.stats
fn main() {
println(stats.mode<int>([2, 7, 1, 8, 2]))
println(stats.mode<int>([2, 7, 1, 8, 2, 8]))
}</syntaxhighlight>
{{out}}
<pre>2
2
</pre>
 
=={{header|Wren}}==
<langsyntaxhighlight lang="wren">class Arithmetic {
static mode(arr) {
var map = {}
Line 3,032 ⟶ 3,739:
}
 
System.print(Arithmetic.mode([1,2,3,4,5,5,51,2,3]))</syntaxhighlight>
</lang>
{{out}}
[2, 3, 5]
Line 3,041 ⟶ 3,747:
=={{header|XEmacs Lisp}}==
This returns a list of the modes. Any type(s) of data can be passed in, and any "equal" predicate function can be specified.
<langsyntaxhighlight lang="xelisp">(defun mode ( predicate &rest values)
"Finds the mode of all values passed in.
Uses `predicate' to compare items."
Line 3,058 ⟶ 3,764:
(when (eq count mode-count)
(push value modes))))
modes))</langsyntaxhighlight>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">proc Mode(Size, Array); \Show the mode(s) of Array
int Size, Array;
int List, Count I, J, K, Max;
[List:= Reserve(Size*4); \4 bytes per integer
Count:= Reserve(Size*4);
K:= 0;
for I:= 0 to Size-1 do
[for J:= 0 to K-1 do
if List(J) = Array(I) then \item is in List
[Count(J):= Count(J)+1; \ so increment its count
J:= Size;
];
if J = K then \not already in List
[List(K):= Array(I);
Count(K):= 1;
K:= K+1;
];
];
Max:= 0; \find maximum count
for J:= 0 to K-1 do
if Count(J) > Max then
Max:= Count(J);
for J:= 0 to K-1 do \show Array item(s) with Max Count
if Count(J) = Max then
[IntOut(0, List(J)); ChOut(0, ^ )];
];
 
Mode(9, [1,2,3,4,5,5,5123,2,3])
</syntaxhighlight>
{{out}}
<pre>
2 3 5 </pre>
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">sub floor(x)
return int(x + .05)
end sub
Line 3,126 ⟶ 3,866:
 
result$ = getMode$("a, a, b, d, d")
print "mode ", left$(result$, n - 1), " occur(s) ", right$(result$, len(result$) - n), " times."</langsyntaxhighlight>
 
{{out}}
Line 3,136 ⟶ 3,876:
This is a bit funky in that modes are returned as strings.
{{trans|D}}
<langsyntaxhighlight lang="zkl">fcn mode(items){
d:=Dictionary(); foreach i in (items){ d.incV(i) }
m:=d.reduce(fcn(m,[(_,v)]){ v.max(m) },0);
d.filter('wrap([(_,v)]){ v==m }).apply("get",0);
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">data:=T(1, 2, 3, 1, 2, 4, 2, 5, 3, 3, 1, 3, 6);
println("Mode: ", mode(data));
println("Mode: ", mode(data.append(2)));
println("Mode: ", mode("this is a test".split("")));</langsyntaxhighlight>
{{out}}
<pre>
Anonymous user