Averages/Mode: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1: Line 1:
{{task|Probability and statistics}}
{{task|Probability and statistics}}


;Task
{{task heading}}


Write a program to find the [[wp:Mode (statistics)|mode]] value of a collection.
Write a program to find the [[wp:Mode (statistics)|mode]] value of a collection.
Line 17: Line 17:
=={{header|11l}}==
=={{header|11l}}==
{{trans|Python}}
{{trans|Python}}
<syntaxhighlight lang=11l>F modes(values)
<syntaxhighlight lang="11l">F modes(values)
DefaultDict[Int, Int] count
DefaultDict[Int, Int] count
L(v) values
L(v) values
Line 33: Line 33:


=={{header|Action!}}==
=={{header|Action!}}==
<syntaxhighlight lang=Action!>DEFINE MAX="100"
<syntaxhighlight lang="action!">DEFINE MAX="100"
INT ARRAY keys(MAX)
INT ARRAY keys(MAX)
INT ARRAY values(MAX)
INT ARRAY values(MAX)
Line 142: Line 142:
=={{header|ActionScript}}==
=={{header|ActionScript}}==
This implementation does not work with arbitrary collections. However, it works with arrays containing mixed data, including strings and other arrays.
This implementation does not work with arbitrary collections. However, it works with arrays containing mixed data, including strings and other arrays.
<syntaxhighlight lang=ActionScript>function Mode(arr:Array):Array {
<syntaxhighlight lang="actionscript">function Mode(arr:Array):Array {
//Create an associative array to count how many times each element occurs,
//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.
//an array to contain the modes, and a variable to store how many times each mode appears.
Line 174: Line 174:
{{works with|Ada 2005}}
{{works with|Ada 2005}}
mode.ads:
mode.ads:
<syntaxhighlight lang=Ada>generic
<syntaxhighlight lang="ada">generic
type Element_Type is private;
type Element_Type is private;
type Element_Array is array (Positive range <>) of Element_Type;
type Element_Array is array (Positive range <>) of Element_Type;
Line 183: Line 183:
end Mode;</syntaxhighlight>
end Mode;</syntaxhighlight>
mode.adb:
mode.adb:
<syntaxhighlight lang=Ada>with Ada.Containers.Indefinite_Vectors;
<syntaxhighlight lang="ada">with Ada.Containers.Indefinite_Vectors;


package body Mode is
package body Mode is
Line 286: Line 286:
end Mode;</syntaxhighlight>
end Mode;</syntaxhighlight>
example use:
example use:
<syntaxhighlight lang=Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;
with Mode;
with Mode;
procedure Main is
procedure Main is
Line 317: Line 317:


=={{header|APL}}==
=={{header|APL}}==
<syntaxhighlight lang=APL>mode←{{s←⌈/⍵[;2]⋄⊃¨(↓⍵)∩{⍵,s}¨⍵[;1]}{⍺,≢⍵}⌸⍵}</syntaxhighlight>
<syntaxhighlight lang="apl">mode←{{s←⌈/⍵[;2]⋄⊃¨(↓⍵)∩{⍵,s}¨⍵[;1]}{⍺,≢⍵}⌸⍵}</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
Line 323: Line 323:
This works with both lists and records containing numbers and/or text values.
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).
<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
use sorter : script "Shell sort" -- https://www.rosettacode.org/wiki/Sorting_algorithms/Shell_sort#AppleScript


Line 377: Line 377:
=={{header|Arturo}}==
=={{header|Arturo}}==


<syntaxhighlight lang=rebol>getMode: function [arr][
<syntaxhighlight lang="rebol">getMode: function [arr][
freqs: new #[]
freqs: new #[]
loop arr 'i [
loop arr 'i [
Line 399: Line 399:
{{AutoHotkey case}}
{{AutoHotkey case}}
Source: [http://www.autohotkey.com/forum/post-276175.html#276175 AutoHotkey forum] by Laszlo
Source: [http://www.autohotkey.com/forum/post-276175.html#276175 AutoHotkey forum] by Laszlo
<syntaxhighlight lang=autohotkey>MsgBox % Mode("1 2 3")
<syntaxhighlight lang="autohotkey">MsgBox % Mode("1 2 3")
MsgBox % Mode("1 2 0 3 0.0")
MsgBox % Mode("1 2 0 3 0.0")
MsgBox % Mode("0.1 2.2 -0.1 0.22e1 2.20 0.1")
MsgBox % Mode("0.1 2.2 -0.1 0.22e1 2.20 0.1")
Line 417: Line 417:
=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang=AWK>#!/usr/bin/gawk -f
<syntaxhighlight lang="awk">#!/usr/bin/gawk -f
{
{
# compute histogram
# compute histogram
Line 466: Line 466:


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<syntaxhighlight lang=bbcbasic> DIM a(10), b(4)
<syntaxhighlight lang="bbcbasic"> DIM a(10), b(4)
a() = 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17
a() = 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17
b() = 1, 2, 4, 4, 1
b() = 1, 2, 4, 4, 1
Line 519: Line 519:
=={{header|C}}==
=={{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.
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.
<syntaxhighlight lang=C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>


Line 584: Line 584:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<syntaxhighlight lang=csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Generic;
Line 626: Line 626:
=={{header|C++}}==
=={{header|C++}}==
{{works with|g++|4.3.2}}
{{works with|g++|4.3.2}}
<syntaxhighlight lang=cpp>#include <iterator>
<syntaxhighlight lang="cpp">#include <iterator>
#include <utility>
#include <utility>
#include <algorithm>
#include <algorithm>
Line 698: Line 698:


=={{header|Clojure}}==
=={{header|Clojure}}==
<syntaxhighlight lang=clojure>(defn modes [coll]
<syntaxhighlight lang="clojure">(defn modes [coll]
(let [distrib (frequencies coll)
(let [distrib (frequencies coll)
[value freq] [first second] ; name the key/value pairs in the distrib (map) entries
[value freq] [first second] ; name the key/value pairs in the distrib (map) entries
Line 705: Line 705:
(map value (take-while #(= maxfq (freq %)) sorted))))</syntaxhighlight>
(map value (take-while #(= maxfq (freq %)) sorted))))</syntaxhighlight>
Or a one-liner solution
Or a one-liner solution
<syntaxhighlight lang=clojure>(defn modes [coll]
<syntaxhighlight lang="clojure">(defn modes [coll]
(->> coll frequencies (sort-by val >) (partition-by val) first (map key)))</syntaxhighlight>
(->> coll frequencies (sort-by val >) (partition-by val) first (map key)))</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<syntaxhighlight lang=coffeescript>mode = (arr) ->
<syntaxhighlight lang="coffeescript">mode = (arr) ->
# returns an array with the modes of arr, i.e. the
# returns an array with the modes of arr, i.e. the
# elements that appear most often in arr
# elements that appear most often in arr
Line 725: Line 725:
=={{header|Common Lisp}}==
=={{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.
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.
<syntaxhighlight lang=lisp>(defun mode (sequence &rest hash-table-options)
<syntaxhighlight lang="lisp">(defun mode (sequence &rest hash-table-options)
(let ((frequencies (apply #'make-hash-table hash-table-options)))
(let ((frequencies (apply #'make-hash-table hash-table-options)))
(map nil (lambda (element)
(map nil (lambda (element)
Line 743: Line 743:
=={{header|D}}==
=={{header|D}}==
The mode function returns a range of all the mode items:
The mode function returns a range of all the mode items:
<syntaxhighlight lang=d>import std.stdio, std.algorithm, std.array;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.array;


auto mode(T)(T[] items) pure /*nothrow @safe*/ {
auto mode(T)(T[] items) pure /*nothrow @safe*/ {
Line 766: Line 766:
{{libheader| System.Generics.Collections}}
{{libheader| System.Generics.Collections}}
{{libheader| System.Generics.Defaults}}
{{libheader| System.Generics.Defaults}}
<syntaxhighlight lang=Delphi>
<syntaxhighlight lang="delphi">
program AveragesMode;
program AveragesMode;


Line 844: Line 844:
Value: 12, Count: 4</pre>
Value: 12, Count: 4</pre>
=={{header|E}}==
=={{header|E}}==
<syntaxhighlight lang=e>pragma.enable("accumulator")
<syntaxhighlight lang="e">pragma.enable("accumulator")
def mode(values) {
def mode(values) {
def counts := [].asMap().diverge()
def counts := [].asMap().diverge()
Line 853: Line 853:
return accum [].asSet() for v => ==maxCount in counts { _.with(v) }
return accum [].asSet() for v => ==maxCount in counts { _.with(v) }
}</syntaxhighlight>
}</syntaxhighlight>
<syntaxhighlight lang=e>? mode([1,1,2,2,3,3,4,4,4,5,5,6,6,7,8,8,9,9,0,0,0])
<syntaxhighlight 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()</syntaxhighlight>
# value: [4, 0].asSet()</syntaxhighlight>
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:
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:
<syntaxhighlight lang=e> def newCount := counts.fetch(v, fn { 0 }) + 1
<syntaxhighlight lang="e"> def newCount := counts.fetch(v, fn { 0 }) + 1
counts[v] := newCount
counts[v] := newCount
maxCount := maxCount.max(newCount)</syntaxhighlight>
maxCount := maxCount.max(newCount)</syntaxhighlight>
Line 862: Line 862:


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<syntaxhighlight lang=scheme>
<syntaxhighlight lang="scheme">
(define (modes L)
(define (modes L)
(define G (group* L)) ;; sorts and group equal items
(define G (group* L)) ;; sorts and group equal items
Line 883: Line 883:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0:
ELENA 5.0:
<syntaxhighlight lang=elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import system'collections;
import system'collections;
import extensions;
import extensions;
Line 928: Line 928:


=={{header|Elixir}}==
=={{header|Elixir}}==
<syntaxhighlight lang=elixir>defmodule Average do
<syntaxhighlight lang="elixir">defmodule Average do
def mode(list) do
def mode(list) do
gb = Enum.group_by(list, &(&1))
gb = Enum.group_by(list, &(&1))
Line 952: Line 952:


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang=Erlang>
<syntaxhighlight lang="erlang">
-module( mode ).
-module( mode ).
-export( [example/0, values/1] ).
-export( [example/0, values/1] ).
Line 982: Line 982:


=={{header|ERRE}}==
=={{header|ERRE}}==
<syntaxhighlight lang=ERRE>PROGRAM MODE_AVG
<syntaxhighlight lang="erre">PROGRAM MODE_AVG


!$INTEGER
!$INTEGER
Line 1,050: Line 1,050:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<syntaxhighlight lang=euphoria>include misc.e
<syntaxhighlight lang="euphoria">include misc.e


function mode(sequence s)
function mode(sequence s)
Line 1,098: Line 1,098:
=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
The Unchecked.defaultof became available in version 1.9.4 I think.
The Unchecked.defaultof became available in version 1.9.4 I think.
<syntaxhighlight lang=fsharp>let mode (l:'a seq) =
<syntaxhighlight lang="fsharp">let mode (l:'a seq) =
l
l
|> Seq.countBy (fun item -> item) // Count individual items
|> Seq.countBy (fun item -> item) // Count individual items
Line 1,109: Line 1,109:
|> snd // From (count, list) we just want the second item (the list)</syntaxhighlight>
|> snd // From (count, list) we just want the second item (the list)</syntaxhighlight>
Example usage:
Example usage:
<syntaxhighlight lang=fsharp>> mode ["a"; "b"; "c"; "c"];;
<syntaxhighlight lang="fsharp">> mode ["a"; "b"; "c"; "c"];;
val it : string list = ["c"]
val it : string list = ["c"]
> mode ["a"; "b"; "c"; "c";"a"];;
> mode ["a"; "b"; "c"; "c";"a"];;
Line 1,118: Line 1,118:
=={{header|Factor}}==
=={{header|Factor}}==
Factor has the word <code>mode</code> in <code>math.statistics</code> vocabulary.
Factor has the word <code>mode</code> in <code>math.statistics</code> vocabulary.
<syntaxhighlight lang=factor>{ 11 9 4 9 4 9 } mode ! 9 </syntaxhighlight>
<syntaxhighlight lang="factor">{ 11 9 4 9 4 9 } mode ! 9 </syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
For the <tt>Qsort_Module</tt> see [[Sorting_algorithms/Quicksort#Fortran]]
For the <tt>Qsort_Module</tt> see [[Sorting_algorithms/Quicksort#Fortran]]
<syntaxhighlight lang=fortran>program mode_test
<syntaxhighlight lang="fortran">program mode_test
use Qsort_Module only Qsort => sort
use Qsort_Module only Qsort => sort
implicit none
implicit none
Line 1,223: Line 1,223:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<syntaxhighlight lang=freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Sub quicksort(a() As Integer, first As Integer, last As Integer)
Sub quicksort(a() As Integer, first As Integer, last As Integer)
Line 1,298: Line 1,298:


=={{header|Frink}}==
=={{header|Frink}}==
<syntaxhighlight lang=frink>modes[vals] :=
<syntaxhighlight lang="frink">modes[vals] :=
{
{
count = countToArray[vals]
count = countToArray[vals]
Line 1,321: Line 1,321:
</pre>
</pre>
As of the 2022-07-31 release of Frink, the function can be rewritten as:
As of the 2022-07-31 release of Frink, the function can be rewritten as:
<syntaxhighlight lang=frink>modes[vals] := mostCommon[vals]@0</syntaxhighlight>
<syntaxhighlight lang="frink">modes[vals] := mostCommon[vals]@0</syntaxhighlight>


=={{header|GAP}}==
=={{header|GAP}}==
<syntaxhighlight lang=gap>mode := function(v)
<syntaxhighlight lang="gap">mode := function(v)
local c, m;
local c, m;
c := Collected(SortedList(v));
c := Collected(SortedList(v));
Line 1,336: Line 1,336:
=={{header|Go}}==
=={{header|Go}}==
'''Fixed collection type, fixed value type.''' In Go it is appropriate to program directly with built in types when possible.
'''Fixed collection type, fixed value type.''' In Go it is appropriate to program directly with built in types when possible.
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,370: Line 1,370:
</pre>
</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.
'''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.
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,404: Line 1,404:
</pre>
</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.
'''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.
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,467: Line 1,467:
</pre>
</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.
'''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.
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,543: Line 1,543:
=={{header|Groovy}}==
=={{header|Groovy}}==
Solution, both "collection type" and "element type" agnostic:
Solution, both "collection type" and "element type" agnostic:
<syntaxhighlight lang=groovy>def mode(Iterable col) {
<syntaxhighlight lang="groovy">def mode(Iterable col) {
assert col
assert col
def m = [:]
def m = [:]
Line 1,553: Line 1,553:
}</syntaxhighlight>
}</syntaxhighlight>
Test:
Test:
<syntaxhighlight lang=groovy>def random = new Random()
<syntaxhighlight lang="groovy">def random = new Random()
def sourceList = [ 'Lamp', 42.0, java.awt.Color.RED, new Date(), ~/pattern/]
def sourceList = [ 'Lamp', 42.0, java.awt.Color.RED, new Date(), ~/pattern/]
(0..10).each {
(0..10).each {
Line 1,573: Line 1,573:


=={{header|Haskell}}==
=={{header|Haskell}}==
<syntaxhighlight lang=haskell>import Prelude (foldr, maximum, (==), (+))
<syntaxhighlight lang="haskell">import Prelude (foldr, maximum, (==), (+))
import Data.Map (insertWith', empty, filter, elems, keys)
import Data.Map (insertWith', empty, filter, elems, keys)


Line 1,585: Line 1,585:
[1,2,3]
[1,2,3]
Alternately:
Alternately:
<syntaxhighlight lang=haskell>import Data.List (group, sort)
<syntaxhighlight lang="haskell">import Data.List (group, sort)


mode :: (Ord a) => [a] -> [a]
mode :: (Ord a) => [a] -> [a]
Line 1,592: Line 1,592:
best = maximum (map snd counts)</syntaxhighlight>
best = maximum (map snd counts)</syntaxhighlight>
Another version that does not require an orderable type:
Another version that does not require an orderable type:
<syntaxhighlight lang=haskell>import Data.List (partition)
<syntaxhighlight lang="haskell">import Data.List (partition)


mode :: (Eq a) => [a] -> [a]
mode :: (Eq a) => [a] -> [a]
Line 1,606: Line 1,606:
=={{header|Icon}} and {{header|Unicon}}==
=={{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.
The <tt>mode</tt> procedure generates all <i>n</i> mode values if the collection is <i>n</i>-modal.
<syntaxhighlight lang=icon>procedure main(args)
<syntaxhighlight lang="icon">procedure main(args)
every write(!mode(args))
every write(!mode(args))
end
end
Line 1,629: Line 1,629:


=={{header|J}}==
=={{header|J}}==
<syntaxhighlight lang=j>mode=: ~. #~ ( = >./ )@( #/.~ )</syntaxhighlight>
<syntaxhighlight lang="j">mode=: ~. #~ ( = >./ )@( #/.~ )</syntaxhighlight>


Literally: select from the unique values the values which appear the most often.
Literally: select from the unique values the values which appear the most often.
Line 1,643: Line 1,643:


=={{header|Java}}==
=={{header|Java}}==
<syntaxhighlight lang=java>import java.util.*;
<syntaxhighlight lang="java">import java.util.*;


public class Mode {
public class Mode {
Line 1,673: Line 1,673:


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<syntaxhighlight lang=javascript>function mode(ary) {
<syntaxhighlight lang="javascript">function mode(ary) {
var counter = {};
var counter = {};
var mode = [];
var mode = [];
Line 1,697: Line 1,697:
=={{header|jq}}==
=={{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 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.<syntaxhighlight lang=jq># modes/0 produces an array of [value, count]
jq's <tt>sort</tt> is very fast in any case.<syntaxhighlight lang="jq"># modes/0 produces an array of [value, count]
# in increasing order of count:
# in increasing order of count:
def modes:
def modes:
Line 1,715: Line 1,715:
| $modes[-1][1] as $count
| $modes[-1][1] as $count
| $modes[] | select( .[1] == $count) | .[0]
| $modes[] | select( .[1] == $count) | .[0]
end;</syntaxhighlight>Examples:<syntaxhighlight lang=jq>
end;</syntaxhighlight>Examples:<syntaxhighlight lang="jq">
[1,2,3,1,2,1] | mode # => 1
[1,2,3,1,2,1] | mode # => 1
[1,2,3,1,2,1,2] | mode # => 1 2
[1,2,3,1,2,1,2] | mode # => 1 2
Line 1,721: Line 1,721:


=={{header|Julia}}==
=={{header|Julia}}==
<syntaxhighlight lang=julia>function modes(values)
<syntaxhighlight lang="julia">function modes(values)
dict = Dict() # Values => Number of repetitions
dict = Dict() # Values => Number of repetitions
modesArray = typeof(values[1])[] # Array of the modes so far
modesArray = typeof(values[1])[] # Array of the modes so far
Line 1,752: Line 1,752:


=={{header|K}}==
=={{header|K}}==
<syntaxhighlight lang=k> mode: {(?x)@&n=|/n:#:'=x}
<syntaxhighlight 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
mode 1 1 1 1 2 2 2 3 3 3 3 4 4 3 2 4 4 4
3 4</syntaxhighlight>
3 4</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<syntaxhighlight lang=scala>fun <T> modeOf(a: Array<T>) {
<syntaxhighlight lang="scala">fun <T> modeOf(a: Array<T>) {
val sortedByFreq = a.groupBy { it }.entries.sortedByDescending { it.value.size }
val sortedByFreq = a.groupBy { it }.entries.sortedByDescending { it.value.size }
val maxFreq = sortedByFreq.first().value.size
val maxFreq = sortedByFreq.first().value.size
Line 1,789: Line 1,789:


=={{header|Lasso}}==
=={{header|Lasso}}==
<syntaxhighlight lang=Lasso>define getmode(a::array)::array => {
<syntaxhighlight lang="lasso">define getmode(a::array)::array => {
local(mmap = map, maxv = 0, modes = array)
local(mmap = map, maxv = 0, modes = array)
// store counts
// store counts
Line 1,808: Line 1,808:
=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
Using string of integers instead collection.
Using string of integers instead collection.
<syntaxhighlight lang=lb>
<syntaxhighlight lang="lb">
a$ = "1 3 6 6 6 6 7 7 12 12 17"
a$ = "1 3 6 6 6 6 7 7 12 12 17"
b$ = "1 2 4 4 1"
b$ = "1 2 4 4 1"
Line 1,877: Line 1,877:


=={{header|Lua}}==
=={{header|Lua}}==
<syntaxhighlight lang=lua>function mode(tbl) -- returns table of modes and count
<syntaxhighlight lang="lua">function mode(tbl) -- returns table of modes and count
assert(type(tbl) == 'table')
assert(type(tbl) == 'table')
local counts = { }
local counts = { }
Line 1,911: Line 1,911:
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).
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>
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Module Checkit {
\\ find mode
\\ find mode
Line 1,962: Line 1,962:




<syntaxhighlight lang=M2000 Interpreter>
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Module Checkit {
Function GetMode(&a()){
Function GetMode(&a()){
Line 2,014: Line 2,014:
The built-in function Statistics:-Mode can be used to compute a mode.
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:
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:
<syntaxhighlight lang=Maple>Statistics:-Mode([1, 2.1, 2.1, 3]);
<syntaxhighlight lang="maple">Statistics:-Mode([1, 2.1, 2.1, 3]);
Statistics:-Mode([1, 2.1, 2.1, 3.2, 3.2, 5]);</syntaxhighlight>
Statistics:-Mode([1, 2.1, 2.1, 3.2, 3.2, 5]);</syntaxhighlight>


Line 2,024: Line 2,024:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{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:
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:
<syntaxhighlight lang=Mathematica> Commonest[{b, a, c, 2, a, b, 1, 2, 3}]
<syntaxhighlight lang="mathematica"> Commonest[{b, a, c, 2, a, b, 1, 2, 3}]
Commonest[{1, 3, 2, 3}]</syntaxhighlight>
Commonest[{1, 3, 2, 3}]</syntaxhighlight>
{{out}}
{{out}}
Line 2,031: Line 2,031:


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<syntaxhighlight lang=Matlab>function modeValue = findmode(setOfValues)
<syntaxhighlight lang="matlab">function modeValue = findmode(setOfValues)
modeValue = mode(setOfValues);
modeValue = mode(setOfValues);
end</syntaxhighlight>
end</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<syntaxhighlight lang=MUMPS>MODE(X)
<syntaxhighlight lang="mumps">MODE(X)
;X is assumed to be a list of numbers separated by "^"
;X is assumed to be a list of numbers separated by "^"
;I is a loop index
;I is a loop index
Line 2,059: Line 2,059:


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<syntaxhighlight lang=NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 2,157: Line 2,157:


=={{header|Nim}}==
=={{header|Nim}}==
<syntaxhighlight lang=nim>import tables
<syntaxhighlight lang="nim">import tables


proc modes[T](xs: openArray[T]): T =
proc modes[T](xs: openArray[T]): T =
Line 2,173: Line 2,173:
=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
{{Works with|oo2c version2}}
{{Works with|oo2c version2}}
<syntaxhighlight lang=oberon2>
<syntaxhighlight lang="oberon2">
MODULE Mode;
MODULE Mode;
IMPORT
IMPORT
Line 2,262: Line 2,262:


=={{header|Objeck}}==
=={{header|Objeck}}==
<syntaxhighlight lang=objeck>
<syntaxhighlight lang="objeck">
use Collection;
use Collection;


Line 2,316: Line 2,316:


=={{header|Objective-C}}==
=={{header|Objective-C}}==
<syntaxhighlight lang=objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>
@interface NSArray (Mode)
@interface NSArray (Mode)
Line 2,342: Line 2,342:


=={{header|OCaml}}==
=={{header|OCaml}}==
<syntaxhighlight lang=ocaml>let mode lst =
<syntaxhighlight lang="ocaml">let mode lst =
let seen = Hashtbl.create 42 in
let seen = Hashtbl.create 42 in
List.iter (fun x ->
List.iter (fun x ->
Line 2,362: Line 2,362:
=={{header|Octave}}==
=={{header|Octave}}==
Of course Octave has the <tt>mode</tt> function; but it returns only the "lowest" mode if multiple modes are available.
Of course Octave has the <tt>mode</tt> function; but it returns only the "lowest" mode if multiple modes are available.
<syntaxhighlight lang=octave>function m = mode2(v)
<syntaxhighlight lang="octave">function m = mode2(v)
sv = sort(v);
sv = sort(v);
% build two vectors, vals and c, so that
% build two vectors, vals and c, so that
Line 2,391: Line 2,391:
endwhile
endwhile
endfunction</syntaxhighlight>
endfunction</syntaxhighlight>
<syntaxhighlight lang=octave>a = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
<syntaxhighlight lang="octave">a = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
mode2(a)
mode2(a)
mode(a)
mode(a)
Line 2,401: Line 2,401:
=={{header|ooRexx}}==
=={{header|ooRexx}}==
See the example at [[#Version_2|REXX, Version 2]] for a version that returns multiple mode values.
See the example at [[#Version_2|REXX, Version 2]] for a version that returns multiple mode values.
<syntaxhighlight lang=ooRexx>
<syntaxhighlight lang="oorexx">
-- will work with just about any collection...
-- will work with just about any collection...
call testMode .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
call testMode .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
Line 2,437: Line 2,437:


=={{header|Oz}}==
=={{header|Oz}}==
<syntaxhighlight lang=oz>declare
<syntaxhighlight lang="oz">declare
fun {Mode Xs}
fun {Mode Xs}
Freq = {Dictionary.new}
Freq = {Dictionary.new}
Line 2,456: Line 2,456:


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<syntaxhighlight lang=parigp>mode(v)={
<syntaxhighlight lang="parigp">mode(v)={
my(count=1,r=1,b=v[1]);
my(count=1,r=1,b=v[1]);
v=vecsort(v);
v=vecsort(v);
Line 2,474: Line 2,474:


=={{header|Perl}}==
=={{header|Perl}}==
<syntaxhighlight lang=perl>use strict;
<syntaxhighlight lang="perl">use strict;
use List::Util qw(max);
use List::Util qw(max);


Line 2,487: Line 2,487:
}</syntaxhighlight>
}</syntaxhighlight>


<syntaxhighlight lang=perl>print "$_ " foreach mode(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17);
<syntaxhighlight lang="perl">print "$_ " foreach mode(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17);
print "\n";
print "\n";
print "$_ " foreach mode(1, 1, 2, 4, 4);
print "$_ " foreach mode(1, 1, 2, 4, 4);
Line 2,493: Line 2,493:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<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>
<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>
<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>
<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>
Line 2,547: Line 2,547:
=={{header|PHP}}==
=={{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.
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.
<syntaxhighlight lang=php><?php
<syntaxhighlight lang="php"><?php
function mode($arr) {
function mode($arr) {
$count = array_count_values($arr);
$count = array_count_values($arr);
Line 2,559: Line 2,559:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp>(de modes (Lst)
<syntaxhighlight lang="picolisp">(de modes (Lst)
(let A NIL
(let A NIL
(for X Lst
(for X Lst
Line 2,580: Line 2,580:


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang=PL/I>av: procedure options (main); /* 28 October 2013 */
<syntaxhighlight lang="pl/i">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 x(10) fixed binary static initial (1, 4, 2, 6, 2, 5, 6, 2, 4, 2);
declare f(32767) fixed binary;
declare f(32767) fixed binary;
Line 2,606: Line 2,606:


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang=PowerShell>$data = @(1,1,1,2,3,4,5,5,6,7,7,7)
<syntaxhighlight lang="powershell">$data = @(1,1,1,2,3,4,5,5,6,7,7,7)
$groups = $data | group-object | sort-object count -Descending
$groups = $data | group-object | sort-object count -Descending
$groups | ? {$_.Count -eq $groups[0].Count}</syntaxhighlight>
$groups | ? {$_.Count -eq $groups[0].Count}</syntaxhighlight>
Line 2,616: Line 2,616:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic>Procedure mean(Array InArray(1))
<syntaxhighlight lang="purebasic">Procedure mean(Array InArray(1))


Structure MyMean
Structure MyMean
Line 2,658: Line 2,658:
The following solutions require that the elements be ''hashable''.
The following solutions require that the elements be ''hashable''.
{{works with|Python|2.5+ and 3.x}}
{{works with|Python|2.5+ and 3.x}}
<syntaxhighlight lang=python>>>> from collections import defaultdict
<syntaxhighlight lang="python">>>> from collections import defaultdict
>>> def modes(values):
>>> def modes(values):
count = defaultdict(int)
count = defaultdict(int)
Line 2,671: Line 2,671:
[1, 4]</syntaxhighlight>
[1, 4]</syntaxhighlight>
{{works with|Python|2.7+ and 3.1+}}
{{works with|Python|2.7+ and 3.1+}}
<syntaxhighlight lang=python>>>> from collections import Counter
<syntaxhighlight lang="python">>>> from collections import Counter
>>> def modes(values):
>>> def modes(values):
count = Counter(values)
count = Counter(values)
Line 2,682: Line 2,682:
[1, 4]</syntaxhighlight>
[1, 4]</syntaxhighlight>
If you just want one mode (instead of all of them), here's a one-liner for that:
If you just want one mode (instead of all of them), here's a one-liner for that:
<syntaxhighlight lang=python>def onemode(values):
<syntaxhighlight lang="python">def onemode(values):
return max(set(values), key=values.count)</syntaxhighlight>
return max(set(values), key=values.count)</syntaxhighlight>


=={{header|Q}}==
=={{header|Q}}==
<syntaxhighlight lang=q>mode:{(key x) where value x=max x} count each group @</syntaxhighlight>
<syntaxhighlight lang="q">mode:{(key x) where value x=max x} count each group @</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==


<syntaxhighlight lang=Quackery> [ sort
<syntaxhighlight lang="quackery"> [ sort
[] [] rot
[] [] rot
dup 0 peek temp put
dup 0 peek temp put
Line 2,731: Line 2,731:


=={{header|R}}==
=={{header|R}}==
<syntaxhighlight lang=R>statmode <- function(v) {
<syntaxhighlight lang="r">statmode <- function(v) {
a <- sort(table(v), decreasing=TRUE)
a <- sort(table(v), decreasing=TRUE)
r <- c()
r <- c()
Line 2,748: Line 2,748:
=={{header|Racket}}==
=={{header|Racket}}==
Returns values of list of modes and their frequencies of appearance.
Returns values of list of modes and their frequencies of appearance.
<syntaxhighlight lang=Racket>#lang racket
<syntaxhighlight lang="racket">#lang racket


(define (mode seq)
(define (mode seq)
Line 2,771: Line 2,771:


{{works with|Rakudo|2019.03.1}}
{{works with|Rakudo|2019.03.1}}
<syntaxhighlight lang=perl6>sub mode (*@a) {
<syntaxhighlight lang="raku" line>sub mode (*@a) {
my %counts := @a.Bag;
my %counts := @a.Bag;
my $max = %counts.values.max;
my $max = %counts.values.max;
Line 2,789: Line 2,789:
Alternatively, a version that uses a single method chain with no temporary variables: (Same output with same input)
Alternatively, a version that uses a single method chain with no temporary variables: (Same output with same input)


<syntaxhighlight lang=perl6>sub mode (*@a) {
<syntaxhighlight lang="raku" line>sub mode (*@a) {
@a.Bag # count elements
@a.Bag # count elements
.classify(*.value) # group elements with the same count
.classify(*.value) # group elements with the same count
Line 2,802: Line 2,802:
===version 1===
===version 1===
Returns one mode value.
Returns one mode value.
<syntaxhighlight lang=rexx>/*REXX program finds the mode (most occurring element) of a vector. */
<syntaxhighlight lang="rexx">/*REXX program finds the mode (most occurring element) of a vector. */
/* ════════vector═══════════ ═══show vector═══ ═════show result═════ */
/* ════════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
v= 1 8 6 0 1 9 4 6 1 9 9 9 ; say 'vector='v; say 'mode='mode(v); say
Line 2,848: Line 2,848:
{{works with|Regina}}
{{works with|Regina}}
and should work for every REXX.
and should work for every REXX.
<syntaxhighlight lang=REXX>/* Rexx */
<syntaxhighlight lang="rexx">/* Rexx */
/*-- ~~ main ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/*-- ~~ main ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
call run_samples
call run_samples
Line 2,960: Line 2,960:


=={{header|Ring}}==
=={{header|Ring}}==
<syntaxhighlight lang=ring>
<syntaxhighlight lang="ring">
# Project : Averages/Mode
# Project : Averages/Mode


Line 3,014: Line 3,014:
=={{header|Ruby}}==
=={{header|Ruby}}==
Here's two methods, the first more Ruby-ish, the second perhaps a bit more efficient.
Here's two methods, the first more Ruby-ish, the second perhaps a bit more efficient.
<syntaxhighlight lang=ruby>def mode(ary)
<syntaxhighlight lang="ruby">def mode(ary)
seen = Hash.new(0)
seen = Hash.new(0)
ary.each {|value| seen[value] += 1}
ary.each {|value| seen[value] += 1}
Line 3,043: Line 3,043:
{{works with|Ruby|1.8.7}}
{{works with|Ruby|1.8.7}}
If you just want one mode (instead of all of them), here's a one-liner for that:
If you just want one mode (instead of all of them), here's a one-liner for that:
<syntaxhighlight lang=ruby>def one_mode(ary)
<syntaxhighlight lang="ruby">def one_mode(ary)
ary.max_by { |x| ary.count(x) }
ary.max_by { |x| ary.count(x) }
end</syntaxhighlight>
end</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<syntaxhighlight lang=rust>use std::collections::HashMap;
<syntaxhighlight lang="rust">use std::collections::HashMap;


fn main() {
fn main() {
Line 3,089: Line 3,089:
I'm accepting strings and numbers, although I'm converting numbers to strings,
I'm accepting strings and numbers, although I'm converting numbers to strings,
as S-Lang Assoc_Type only accepts strings as keys.
as S-Lang Assoc_Type only accepts strings as keys.
<syntaxhighlight lang=S-lang>private variable mx, mxkey, modedat;
<syntaxhighlight lang="s-lang">private variable mx, mxkey, modedat;


define find_max(key) {
define find_max(key) {
Line 3,135: Line 3,135:
{{works with|Scala|2.8}}
{{works with|Scala|2.8}}
Receiving any collection is easy. Returning the result in the same collection takes some doing.
Receiving any collection is easy. Returning the result in the same collection takes some doing.
<syntaxhighlight lang=scala>import scala.collection.breakOut
<syntaxhighlight lang="scala">import scala.collection.breakOut
import scala.collection.generic.CanBuildFrom
import scala.collection.generic.CanBuildFrom
def mode
def mode
Line 3,148: Line 3,148:
=={{header|Scheme}}==
=={{header|Scheme}}==
{{works with|Berkeley Scheme}}
{{works with|Berkeley Scheme}}
<syntaxhighlight lang=scheme>(define (mode collection)
<syntaxhighlight lang="scheme">(define (mode collection)
(define (helper collection counts)
(define (helper collection counts)
(if (null? collection)
(if (null? collection)
Line 3,167: Line 3,167:
This way the <code>main</code> function can just [http://seed7.sourceforge.net/libraries/enable_output.htm#write%28in_aType%29 write] the mode.
This way the <code>main</code> function can just [http://seed7.sourceforge.net/libraries/enable_output.htm#write%28in_aType%29 write] the mode.


<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const proc: createModeFunction (in type: elemType) is func
const proc: createModeFunction (in type: elemType) is func
Line 3,226: Line 3,226:


=={{header|Sidef}}==
=={{header|Sidef}}==
<syntaxhighlight lang=ruby>func mode(array) {
<syntaxhighlight lang="ruby">func mode(array) {
var c = Hash.new;
var c = Hash.new;
array.each{|i| c{i} := 0 ++};
array.each{|i| c{i} := 0 ++};
Line 3,234: Line 3,234:


'''Calling the function'''
'''Calling the function'''
<syntaxhighlight lang=ruby>say mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]).join(' ');
<syntaxhighlight lang="ruby">say mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]).join(' ');
say mode([1, 1, 2, 4, 4]).join(' ');</syntaxhighlight>
say mode([1, 1, 2, 4, 4]).join(' ');</syntaxhighlight>


Line 3,245: Line 3,245:
If you just want one mode (instead of all of them), here's a one-liner for that:
If you just want one mode (instead of all of them), here's a one-liner for that:


<syntaxhighlight lang=ruby>func one_mode(arr) {
<syntaxhighlight lang="ruby">func one_mode(arr) {
arr.max_by{|i| arr.count(i)};
arr.max_by{|i| arr.count(i)};
}</syntaxhighlight>
}</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<syntaxhighlight lang=Slate>s@(Sequence traits) mode
<syntaxhighlight lang="slate">s@(Sequence traits) mode
[| sortedCounts |
[| sortedCounts |
sortedCounts: (s as: Bag) sortedCounts.
sortedCounts: (s as: Bag) sortedCounts.
Line 3,259: Line 3,259:
{{works with|GNU Smalltalk}}
{{works with|GNU Smalltalk}}
This code is able to find the mode of any collection of any kind of object.
This code is able to find the mode of any collection of any kind of object.
<syntaxhighlight lang=smalltalk>OrderedCollection extend [
<syntaxhighlight lang="smalltalk">OrderedCollection extend [
mode [ |s|
mode [ |s|
s := self asBag sortedByCount.
s := self asBag sortedByCount.
Line 3,272: Line 3,272:


=={{header|SQL}}==
=={{header|SQL}}==
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
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
create table averages (val integer);
create table averages (val integer);
insert into averages values (1);
insert into averages values (1);
Line 3,317: Line 3,317:
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.
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>
<syntaxhighlight lang="swift">
// Extend the Collection protocol. Any type that conforms to extension where its Element type conforms to Hashable will automatically gain this method.
// 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 {
extension Collection where Element: Hashable {
Line 3,350: Line 3,350:
=={{header|Tcl}}==
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
{{works with|Tcl|8.6}}
<syntaxhighlight lang=tcl># Can find the modal value of any vector of values
<syntaxhighlight lang="tcl"># Can find the modal value of any vector of values
proc mode {n args} {
proc mode {n args} {
foreach n [list $n {*}$args] {
foreach n [list $n {*}$args] {
Line 3,372: Line 3,372:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|bash|4.0}}
{{works with|bash|4.0}}
<syntaxhighlight lang=bash>#!/bin/bash
<syntaxhighlight lang="bash">#!/bin/bash


function mode {
function mode {
Line 3,387: Line 3,387:
echo
echo
}</syntaxhighlight>
}</syntaxhighlight>
<syntaxhighlight lang=bash>mode 1 2 1 2 a b a b a 2
<syntaxhighlight lang="bash">mode 1 2 1 2 a b a b a 2
a 2</syntaxhighlight>
a 2</syntaxhighlight>


=={{header|Ursala}}==
=={{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.
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.
<syntaxhighlight lang=Ursala>#import std
<syntaxhighlight lang="ursala">#import std


mode = ~&hS+ leql$^&h+ eql|=@K2
mode = ~&hS+ leql$^&h+ eql|=@K2
Line 3,405: Line 3,405:
=={{header|VBA}}==
=={{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.
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()
<syntaxhighlight lang="vb">Public Sub main()
s = [{1,2,3,3,3,4,4,4,5,5,6}]
s = [{1,2,3,3,3,4,4,4,5,5,6}]
t = WorksheetFunction.Mode_Mult(s)
t = WorksheetFunction.Mode_Mult(s)
Line 3,421: Line 3,421:
The "mode" item and it's count are displayed on status line.
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.
If there are multiple items with the same count, the smallest one is displayed.
<syntaxhighlight lang=vedit>BOF // Copy all data to a new buffer
<syntaxhighlight lang="vedit">BOF // Copy all data to a new buffer
Reg_Copy(10, ALL)
Reg_Copy(10, ALL)
Buf_Switch(Buf_Free)
Buf_Switch(Buf_Free)
Line 3,448: Line 3,448:


=={{header|Vlang}}==
=={{header|Vlang}}==
<syntaxhighlight lang=vlang>fn main() {
<syntaxhighlight lang="vlang">fn main() {
println(mode([2, 7, 1, 8, 2]))
println(mode([2, 7, 1, 8, 2]))
println(mode([2, 7, 1, 8, 2, 8]))
println(mode([2, 7, 1, 8, 2, 8]))
Line 3,479: Line 3,479:
</pre>
</pre>
Or using `math.stats` module
Or using `math.stats` module
<syntaxhighlight lang=vlang>import math.stats
<syntaxhighlight lang="vlang">import math.stats
fn main() {
fn main() {
println(stats.mode<int>([2, 7, 1, 8, 2]))
println(stats.mode<int>([2, 7, 1, 8, 2]))
Line 3,490: Line 3,490:


=={{header|Wren}}==
=={{header|Wren}}==
<syntaxhighlight lang=ecmascript>class Arithmetic {
<syntaxhighlight lang="ecmascript">class Arithmetic {
static mode(arr) {
static mode(arr) {
var map = {}
var map = {}
Line 3,510: Line 3,510:
=={{header|XEmacs Lisp}}==
=={{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.
This returns a list of the modes. Any type(s) of data can be passed in, and any "equal" predicate function can be specified.
<syntaxhighlight lang=xelisp>(defun mode ( predicate &rest values)
<syntaxhighlight lang="xelisp">(defun mode ( predicate &rest values)
"Finds the mode of all values passed in.
"Finds the mode of all values passed in.
Uses `predicate' to compare items."
Uses `predicate' to compare items."
Line 3,530: Line 3,530:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic>sub floor(x)
<syntaxhighlight lang="yabasic">sub floor(x)
return int(x + .05)
return int(x + .05)
end sub
end sub
Line 3,605: Line 3,605:
This is a bit funky in that modes are returned as strings.
This is a bit funky in that modes are returned as strings.
{{trans|D}}
{{trans|D}}
<syntaxhighlight lang=zkl>fcn mode(items){
<syntaxhighlight lang="zkl">fcn mode(items){
d:=Dictionary(); foreach i in (items){ d.incV(i) }
d:=Dictionary(); foreach i in (items){ d.incV(i) }
m:=d.reduce(fcn(m,[(_,v)]){ v.max(m) },0);
m:=d.reduce(fcn(m,[(_,v)]){ v.max(m) },0);
d.filter('wrap([(_,v)]){ v==m }).apply("get",0);
d.filter('wrap([(_,v)]){ v==m }).apply("get",0);
}</syntaxhighlight>
}</syntaxhighlight>
<syntaxhighlight lang=zkl>data:=T(1, 2, 3, 1, 2, 4, 2, 5, 3, 3, 1, 3, 6);
<syntaxhighlight 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));
println("Mode: ", mode(data.append(2)));
println("Mode: ", mode(data.append(2)));