Averages/Mode: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 17:
=={{header|11l}}==
{{trans|Python}}
<langsyntaxhighlight lang=11l>F modes(values)
DefaultDict[Int, Int] count
L(v) values
Line 25:
 
print(modes([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]))
print(modes([1, 1, 2, 4, 4]))</langsyntaxhighlight>
{{out}}
<pre>
Line 33:
 
=={{header|Action!}}==
<langsyntaxhighlight lang=Action!>DEFINE MAX="100"
INT ARRAY keys(MAX)
INT ARRAY values(MAX)
Line 120:
Test(b,9)
Test(c,1)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Mode.png Screenshot from Atari 8-bit computer]
Line 142:
=={{header|ActionScript}}==
This implementation does not work with arbitrary collections. However, it works with arrays containing mixed data, including strings and other arrays.
<langsyntaxhighlight lang=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 169:
}
return modeList;
}</langsyntaxhighlight>
 
=={{header|Ada}}==
{{works with|Ada 2005}}
mode.ads:
<langsyntaxhighlight lang=Ada>generic
type Element_Type is private;
type Element_Array is array (Positive range <>) of Element_Type;
Line 181:
function Get_Mode (Set : Element_Array) return Element_Array;
 
end Mode;</langsyntaxhighlight>
mode.adb:
<langsyntaxhighlight lang=Ada>with Ada.Containers.Indefinite_Vectors;
 
package body Mode is
Line 284:
end Get_Mode;
 
end Mode;</langsyntaxhighlight>
example use:
<langsyntaxhighlight lang=Ada>with Ada.Text_IO;
with Mode;
procedure Main is
Line 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
Line 317:
 
=={{header|APL}}==
<langsyntaxhighlight lang=APL>mode←{{s←⌈/⍵[;2]⋄⊃¨(↓⍵)∩{⍵,s}¨⍵[;1]}{⍺,≢⍵}⌸⍵}</langsyntaxhighlight>
 
=={{header|AppleScript}}==
Line 323:
This works with both lists and records containing numbers and/or text values.
 
<langsyntaxhighlight 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
 
Line 373:
-- 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}</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang=rebol>getMode: function [arr][
freqs: new #[]
loop arr 'i [
Line 389:
print getMode [1 3 6 6 6 6 7 7 12 12 17]
print getMode [1 1 2 4 4]</langsyntaxhighlight>
 
{{out}}
Line 399:
{{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 413:
Else Ct++
Return Ct>MxCt ? V : MxV
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang=AWK>#!/usr/bin/gawk -f
{
# compute histogram
Line 446:
END {
print mode(histo);
};</langsyntaxhighlight>
 
<pre>cat modedata.txt
Line 466:
 
=={{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 499:
NEXT
= J%
</syntaxhighlight>
</lang>
{{out}}
<pre>Mode(s) of a() = 6
Line 519:
=={{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 lang=C>#include <stdio.h>
#include <stdlib.h>
 
Line 577:
free(vc);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>got 2 modes:
Line 584:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang=csharp>using System;
using System.Collections;
using System.Collections.Generic;
Line 622:
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
{{works with|g++|4.3.2}}
<langsyntaxhighlight lang=cpp>#include <iterator>
#include <utility>
#include <algorithm>
Line 693:
std::cout << std::endl;
return 0;
}</langsyntaxhighlight>
{{out}}
2 3
 
=={{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
<langsyntaxhighlight lang=clojure>(defn modes [coll]
(->> coll frequencies (sort-by val >) (partition-by val) first (map key)))</langsyntaxhighlight>
 
=={{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 721:
(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 739:
(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 759:
data ~= 2;
writeln("Mode: ", data.mode);
}</langsyntaxhighlight>
{{out}}
<pre>Mode: [3]
Line 766:
{{libheader| System.Generics.Collections}}
{{libheader| System.Generics.Defaults}}
<langsyntaxhighlight lang=Delphi>
program AveragesMode;
 
Line 838:
dict.Free;
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>Modes:
Line 844:
Value: 12, Count: 4</pre>
=={{header|E}}==
<langsyntaxhighlight lang=e>pragma.enable("accumulator")
def mode(values) {
def counts := [].asMap().diverge()
Line 852:
}
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|EchoLisp}}==
<langsyntaxhighlight lang=scheme>
(define (modes L)
(define G (group* L)) ;; sorts and group equal items
Line 879:
(modes '())
😖️ error: group : expected list : null 🔎 'modes'
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 5.0:
<langsyntaxhighlight lang=elena>import system'routines;
import system'collections;
import extensions;
Line 919:
.printLine("mode of (",array3.asEnumerable(),") is (",array3.Mode,")")
.readChar()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 928:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang=elixir>defmodule Average do
def mode(list) do
gb = Enum.group_by(list, &(&1))
Line 941:
IO.puts "mode: #{inspect list}"
IO.puts " => #{inspect Average.mode(list)}"
end)</langsyntaxhighlight>
 
{{out}}
Line 952:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang=Erlang>
-module( mode ).
-export( [example/0, values/1] ).
Line 974:
 
values_count( Value, Dict ) -> dict:update_counter( Value, 1, Dict ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 982:
 
=={{header|ERRE}}==
<langsyntaxhighlight lang=ERRE>PROGRAM MODE_AVG
 
!$INTEGER
Line 1,042:
CALC_MODE(B[],4->MODES$)
PRINT(MODES$)
END PROGRAM</langsyntaxhighlight>
{{out}}
<pre>
Line 1,050:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang=euphoria>include misc.e
 
function mode(sequence s)
Line 1,088:
 
constant s = { 1, "blue", 2, 7.5, 5, "green", "red", 5, 2, "blue", "white" }
pretty_print(1,mode(s),{3})</langsyntaxhighlight>
{{out}}
<pre>{
Line 1,098:
=={{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 1,107:
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 1,220:
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 1,288:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,298:
 
=={{header|Frink}}==
<langsyntaxhighlight lang=frink>modes[vals] :=
{
count = countToArray[vals]
Line 1,314:
 
println[modes[[1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]]]
println[modes[[1, 1, 2, 4, 4]]]</langsyntaxhighlight>
{{out}}
<pre>
Line 1,321:
</pre>
As of the 2022-07-31 release of Frink, the function can be rewritten as:
<langsyntaxhighlight lang=frink>modes[vals] := mostCommon[vals]@0</langsyntaxhighlight>
 
=={{header|GAP}}==
<langsyntaxhighlight lang=gap>mode := function(v)
local c, m;
c := Collected(SortedList(v));
Line 1,332:
 
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,363:
}
return mode
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,370:
</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,397:
}
return mode
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,404:
</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,460:
}
return mode
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,467:
</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,533:
}
return mode
}</langsyntaxhighlight>
{{out}}
("Enzyklopädie" has no repeated letters. All are modal.)
Line 1,543:
=={{header|Groovy}}==
Solution, both "collection type" and "element type" agnostic:
<langsyntaxhighlight lang=groovy>def mode(Iterable col) {
assert col
def m = [:]
Line 1,551:
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,573:
 
=={{header|Haskell}}==
<langsyntaxhighlight 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</langsyntaxhighlight>
''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]
Line 1,585:
[1,2,3]
Alternately:
<langsyntaxhighlight 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)</langsyntaxhighlight>
Another version that does not require an orderable type:
<langsyntaxhighlight lang=haskell>import Data.List (partition)
 
mode :: (Eq a) => [a] -> [a]
Line 1,602:
| otherwise = (best, x:modes)
where (xs, notxs) = partition (== x) l
(best, modes) = modesWithCount notxs</langsyntaxhighlight>
 
=={{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,619:
else fail
}
end</langsyntaxhighlight>
{{out|Sample outputs}}
<pre>->am 3 1 4 1 5 9 7 6
Line 1,629:
 
=={{header|J}}==
<langsyntaxhighlight lang=j>mode=: ~. #~ ( = >./ )@( #/.~ )</langsyntaxhighlight>
 
Literally: select from the unique values the values which appear the most often.
Line 1,643:
 
=={{header|Java}}==
<langsyntaxhighlight lang=java>import java.util.*;
 
public class Mode {
Line 1,670:
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,693:
 
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,715:
| $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 lang=julia>function modes(values)
dict = Dict() # Values => Number of repetitions
modesArray = typeof(values[1])[] # Array of the modes so far
Line 1,749:
 
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,777:
println("[" + b.joinToString(", ") + "]")
modeOf(b)
}</langsyntaxhighlight>
 
{{out}}
Line 1,789:
 
=={{header|Lasso}}==
<langsyntaxhighlight lang=Lasso>define getmode(a::array)::array => {
local(mmap = map, maxv = 0, modes = array)
// store counts
Line 1,800:
}
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,808:
=={{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,866:
modes$ = modes$; oldVal; " "
end select
end function </langsyntaxhighlight>
 
{{out}}
Line 1,877:
 
=={{header|Lua}}==
<langsyntaxhighlight lang=lua>function mode(tbl) -- returns table of modes and count
assert(type(tbl) == 'table')
local counts = { }
Line 1,904:
for _, val in pairs(modes) do io.write(val..' ') end
print("occur(s) ", count, " times")
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
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).
 
<langsyntaxhighlight lang=M2000 Interpreter>
Module Checkit {
\\ find mode
Line 1,956:
}
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,962:
 
 
<langsyntaxhighlight lang=M2000 Interpreter>
Module Checkit {
Function GetMode(&a()){
Line 2,009:
}
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 lang=Maple>Statistics:-Mode([1, 2.1, 2.1, 3]);
Statistics:-Mode([1, 2.1, 2.1, 3.2, 3.2, 5]);</langsyntaxhighlight>
 
{{out}}
Line 2,024:
=={{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 lang=Mathematica> Commonest[{b, a, c, 2, a, b, 1, 2, 3}]
Commonest[{1, 3, 2, 3}]</langsyntaxhighlight>
{{out}}
<pre> {b,a,2}
Line 2,031:
 
=={{header|MATLAB}}==
<langsyntaxhighlight lang=Matlab>function modeValue = findmode(setOfValues)
modeValue = mode(setOfValues);
end</langsyntaxhighlight>
 
=={{header|MUMPS}}==
<langsyntaxhighlight lang=MUMPS>MODE(X)
;X is assumed to be a list of numbers separated by "^"
;I is a loop index
Line 2,050:
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 2,059:
 
=={{header|NetRexx}}==
<langsyntaxhighlight lang=NetRexx>/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,134:
show_mode([Rexx 1, 1, 2, 4, 4]) -- 4 1
return
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 2,157:
 
=={{header|Nim}}==
<langsyntaxhighlight lang=nim>import tables
 
proc modes[T](xs: openArray[T]): T =
Line 2,166:
 
echo modes(@[1,3,6,6,6,6,7,7,12,12,17])
echo modes(@[1,1,2,4,4])</langsyntaxhighlight>
Output:
<pre>6
Line 2,173:
=={{header|Oberon-2}}==
{{Works with|oo2c version2}}
<langsyntaxhighlight lang=oberon2>
MODULE Mode;
IMPORT
Line 2,250:
Show(Mode(z));Out.Ln;
END Mode.
</syntaxhighlight>
</lang>
{{out}
<pre>
Line 2,262:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang=objeck>
use Collection;
 
Line 2,313:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang=objc>#import <Foundation/Foundation.h>
@interface NSArray (Mode)
Line 2,339:
return maxElems;
}
@end</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang=ocaml>let mode lst =
let seen = Hashtbl.create 42 in
List.iter (fun x ->
Line 2,354:
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,362:
=={{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,390:
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,397:
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.
<langsyntaxhighlight 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,434:
 
return mode
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
<langsyntaxhighlight lang=oz>declare
fun {Mode Xs}
Freq = {Dictionary.new}
Line 2,453:
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,471:
);
if(count>r,v[#v],b)
};</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang=perl>use strict;
use List::Util qw(max);
 
Line 2,485:
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|Phix}}==
<!--<langsyntaxhighlight 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: #000080;font-style:italic;">-- returns a list of the most common values, each of which occurs the same number of times</span>
Line 2,533:
<span style="color: #0000FF;">?</span><span style="color: #000000;">mode</span><span style="color: #0000FF;">({})</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,547:
=={{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,556:
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 lang=PicoLisp>(de modes (Lst)
(let A NIL
(for X Lst
Line 2,565:
(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,580:
 
=={{header|PL/I}}==
<langsyntaxhighlight 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 f(32767) fixed binary;
Line 2,599:
max || ' times.');
 
end av;</langsyntaxhighlight>
Results:
<pre>
Line 2,606:
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang=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,616:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang=PureBasic>Procedure mean(Array InArray(1))
 
Structure MyMean
Line 2,653:
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,669:
[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,680:
[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}}==
<langsyntaxhighlight lang=q>mode:{(key x) where value x=max x} count each group @</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight lang=Quackery> [ sort
[] [] rot
dup 0 peek temp put
Line 2,721:
' [ 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</langsyntaxhighlight>
 
{{out}}
Line 2,731:
 
=={{header|R}}==
<langsyntaxhighlight lang=R>statmode <- function(v) {
a <- sort(table(v), decreasing=TRUE)
r <- c()
Line 2,744:
 
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 lang=Racket>#lang racket
 
(define (mode seq)
Line 2,765:
(values (cons k ms) freq)]
[else
(values ms freq)])))</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 2,771:
 
{{works with|Rakudo|2019.03.1}}
<langsyntaxhighlight lang=perl6>sub mode (*@a) {
my %counts := @a.Bag;
my $max = %counts.values.max;
Line 2,779:
# Testing with arrays:
say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
say mode [1, 1, 2, 4, 4];</langsyntaxhighlight>
 
{{out}}
Line 2,789:
Alternatively, a version that uses a single method chain with no temporary variables: (Same output with same input)
 
<langsyntaxhighlight lang=perl6>sub mode (*@a) {
@a.Bag # count elements
.classify(*.value) # group elements with the same count
Line 2,797:
 
say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
say mode [1, 1, 2, 4, 4];</langsyntaxhighlight>
 
=={{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,827:
end
end /*j*/
return ? /*return the mode of vector to invoker.*/</langsyntaxhighlight>
'''output'''
<pre>
Line 2,848:
{{works with|Regina}}
and should work for every REXX.
<langsyntaxhighlight lang=REXX>/* Rexx */
/*-- ~~ main ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
call run_samples
Line 2,939:
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,960:
 
=={{header|Ring}}==
<langsyntaxhighlight lang=ring>
# Project : Averages/Mode
 
Line 3,003:
next
return j
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,014:
=={{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 3,040:
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 3,079:
vec_mode
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,089:
I'm accepting strings and numbers, although I'm converting numbers to strings,
as S-Lang Assoc_Type only accepts strings as keys.
<langsyntaxhighlight lang=S-lang>private variable mx, mxkey, modedat;
 
define find_max(key) {
Line 3,127:
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 3,135:
{{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 3,144:
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 3,157:
(map car
(filter (lambda (x) (= (cdr x) (apply max (map cdr (helper collection '())))))
(helper collection '())))</langsyntaxhighlight>
 
=={{header|Seed7}}==
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.
 
<langsyntaxhighlight lang=seed7>$ include "seed7_05.s7i";
 
const proc: createModeFunction (in type: elemType) is func
Line 3,217:
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 3,226:
 
=={{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 3,245:
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 lang=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 3,269:
mode displayNl.
#( 1 1 2 4 4) asOrderedCollection
mode displayNl.</langsyntaxhighlight>
 
=={{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.<langsyntaxhighlight lang=sql>-- setup
create table averages (val integer);
insert into averages values (1);
Line 3,305:
counts
where
num in (select max(num) from counts);</langsyntaxhighlight>
{{out}}
<pre> MODE_VAL
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.
 
<langsyntaxhighlight 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 3,346:
emptyArray.mode() // returns nil
 
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang=tcl># Can find the modal value of any vector of values
proc mode {n args} {
foreach n [list $n {*}$args] {
Line 3,367:
# Testing
puts [mode 1 3 6 6 6 6 7 7 12 12 17]; # --> 6
puts [mode 1 1 2 4 4]; # --> 1 4</langsyntaxhighlight>
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 3,386:
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 lang=Ursala>#import std
 
mode = ~&hS+ leql$^&h+ eql|=@K2
Line 3,398:
#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}}
Line 3,405:
=={{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.
<langsyntaxhighlight lang=vb>Public Sub main()
s = [{1,2,3,3,3,4,4,4,5,5,6}]
t = WorksheetFunction.Mode_Mult(s)
Line 3,411:
Debug.Print x;
Next x
End Sub</langsyntaxhighlight>{{out}}
<pre> 3 4</pre>
 
Line 3,421:
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,445:
Reg_Copy_Block(10, CP, EOL_pos)
Buf_Quit(OK)
Statline_Message(@10)</langsyntaxhighlight>
 
=={{header|Vlang}}==
<langsyntaxhighlight lang=vlang>fn main() {
println(mode([2, 7, 1, 8, 2]))
println(mode([2, 7, 1, 8, 2, 8]))
Line 3,473:
}
return mode
}</langsyntaxhighlight>
{{out}}
<pre>[2]
Line 3,479:
</pre>
Or using `math.stats` module
<langsyntaxhighlight 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]))
}</langsyntaxhighlight>
{{out}}
<pre>2
Line 3,490:
 
=={{header|Wren}}==
<langsyntaxhighlight lang=ecmascript>class Arithmetic {
static mode(arr) {
var map = {}
Line 3,502:
}
 
System.print(Arithmetic.mode([1,2,3,4,5,5,51,2,3]))</langsyntaxhighlight>
{{out}}
[2, 3, 5]
Line 3,510:
=={{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,527:
(when (eq count mode-count)
(push value modes))))
modes))</langsyntaxhighlight>
 
=={{header|Yabasic}}==
<langsyntaxhighlight lang=Yabasic>sub floor(x)
return int(x + .05)
end sub
Line 3,595:
 
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,605:
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>
10,327

edits