Averages/Mode: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 17: | Line 17: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang=11l>F modes(values) |
||
DefaultDict[Int, Int] count |
DefaultDict[Int, Int] count |
||
L(v) values |
L(v) values |
||
Line 25: | Line 25: | ||
print(modes([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])) |
print(modes([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])) |
||
print(modes([1, 1, 2, 4, 4]))</ |
print(modes([1, 1, 2, 4, 4]))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 33: | Line 33: | ||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang=Action!>DEFINE MAX="100" |
||
INT ARRAY keys(MAX) |
INT ARRAY keys(MAX) |
||
INT ARRAY values(MAX) |
INT ARRAY values(MAX) |
||
Line 120: | Line 120: | ||
Test(b,9) |
Test(b,9) |
||
Test(c,1) |
Test(c,1) |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Mode.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Mode.png Screenshot from Atari 8-bit computer] |
||
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 { |
||
//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 169: | Line 169: | ||
} |
} |
||
return modeList; |
return modeList; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
{{works with|Ada 2005}} |
{{works with|Ada 2005}} |
||
mode.ads: |
mode.ads: |
||
< |
<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 181: | Line 181: | ||
function Get_Mode (Set : Element_Array) return Element_Array; |
function Get_Mode (Set : Element_Array) return Element_Array; |
||
end Mode;</ |
end Mode;</syntaxhighlight> |
||
mode.adb: |
mode.adb: |
||
< |
<syntaxhighlight lang=Ada>with Ada.Containers.Indefinite_Vectors; |
||
package body Mode is |
package body Mode is |
||
Line 284: | Line 284: | ||
end Get_Mode; |
end Get_Mode; |
||
end Mode;</ |
end Mode;</syntaxhighlight> |
||
example use: |
example use: |
||
< |
<syntaxhighlight lang=Ada>with Ada.Text_IO; |
||
with Mode; |
with Mode; |
||
procedure Main is |
procedure Main is |
||
Line 311: | Line 311: | ||
end loop; |
end loop; |
||
Ada.Text_IO.New_Line; |
Ada.Text_IO.New_Line; |
||
end Main;</ |
end Main;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Input: 1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6 |
<pre>Input: 1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6 |
||
Line 317: | Line 317: | ||
=={{header|APL}}== |
=={{header|APL}}== |
||
< |
<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). |
||
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 373: | Line 373: | ||
-- With a record: |
-- 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}) |
modeOf({a:12, b:4, c:"rhubarb", d:88, e:"rhubarb", f:17, g:"custard", h:4.0, i:4, j:88}) |
||
--> {4}</ |
--> {4}</syntaxhighlight> |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang=rebol>getMode: function [arr][ |
||
freqs: new #[] |
freqs: new #[] |
||
loop arr 'i [ |
loop arr 'i [ |
||
Line 389: | Line 389: | ||
print getMode [1 3 6 6 6 6 7 7 12 12 17] |
print getMode [1 3 6 6 6 6 7 7 12 12 17] |
||
print getMode [1 1 2 4 4]</ |
print getMode [1 1 2 4 4]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
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") |
||
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 413: | Line 413: | ||
Else Ct++ |
Else Ct++ |
||
Return Ct>MxCt ? V : MxV |
Return Ct>MxCt ? V : MxV |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang=AWK>#!/usr/bin/gawk -f |
||
{ |
{ |
||
# compute histogram |
# compute histogram |
||
Line 446: | Line 446: | ||
END { |
END { |
||
print mode(histo); |
print mode(histo); |
||
};</ |
};</syntaxhighlight> |
||
<pre>cat modedata.txt |
<pre>cat modedata.txt |
||
Line 466: | Line 466: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
< |
<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 499: | Line 499: | ||
NEXT |
NEXT |
||
= J% |
= J% |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>Mode(s) of a() = 6 |
<pre>Mode(s) of a() = 6 |
||
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> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
Line 577: | Line 577: | ||
free(vc); |
free(vc); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>got 2 modes: |
<pre>got 2 modes: |
||
Line 584: | Line 584: | ||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang=csharp>using System; |
||
using System.Collections; |
using System.Collections; |
||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
Line 622: | Line 622: | ||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
{{works with|g++|4.3.2}} |
{{works with|g++|4.3.2}} |
||
< |
<syntaxhighlight lang=cpp>#include <iterator> |
||
#include <utility> |
#include <utility> |
||
#include <algorithm> |
#include <algorithm> |
||
Line 693: | Line 693: | ||
std::cout << std::endl; |
std::cout << std::endl; |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
2 3 |
2 3 |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<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 |
||
sorted (sort-by (comp - freq) distrib) |
sorted (sort-by (comp - freq) distrib) |
||
maxfq (freq (first sorted))] |
maxfq (freq (first sorted))] |
||
(map value (take-while #(= maxfq (freq %)) sorted))))</ |
(map value (take-while #(= maxfq (freq %)) sorted))))</syntaxhighlight> |
||
Or a one-liner solution |
Or a one-liner solution |
||
< |
<syntaxhighlight lang=clojure>(defn modes [coll] |
||
(->> coll frequencies (sort-by val >) (partition-by val) first (map key)))</ |
(->> coll frequencies (sort-by val >) (partition-by val) first (map key)))</syntaxhighlight> |
||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<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 721: | Line 721: | ||
(key for key, cnt of counts when cnt == max) |
(key for key, cnt of counts when cnt == max) |
||
console.log mode [1, 2, 2, 2, 3, 3, 3, 4, 4]</ |
console.log mode [1, 2, 2, 2, 3, 3, 3, 4, 4]</syntaxhighlight> |
||
=={{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) |
||
(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 739: | Line 739: | ||
(push element modes)))) |
(push element modes)))) |
||
frequencies) |
frequencies) |
||
(values modes hifreq))))</ |
(values modes hifreq))))</syntaxhighlight> |
||
=={{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; |
||
auto mode(T)(T[] items) pure /*nothrow @safe*/ { |
auto mode(T)(T[] items) pure /*nothrow @safe*/ { |
||
Line 759: | Line 759: | ||
data ~= 2; |
data ~= 2; |
||
writeln("Mode: ", data.mode); |
writeln("Mode: ", data.mode); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Mode: [3] |
<pre>Mode: [3] |
||
Line 766: | Line 766: | ||
{{libheader| System.Generics.Collections}} |
{{libheader| System.Generics.Collections}} |
||
{{libheader| System.Generics.Defaults}} |
{{libheader| System.Generics.Defaults}} |
||
< |
<syntaxhighlight lang=Delphi> |
||
program AveragesMode; |
program AveragesMode; |
||
Line 838: | Line 838: | ||
dict.Free; |
dict.Free; |
||
Readln; |
Readln; |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Modes: |
<pre>Modes: |
||
Line 844: | Line 844: | ||
Value: 12, Count: 4</pre> |
Value: 12, Count: 4</pre> |
||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang=e>pragma.enable("accumulator") |
||
def mode(values) { |
def mode(values) { |
||
def counts := [].asMap().diverge() |
def counts := [].asMap().diverge() |
||
Line 852: | Line 852: | ||
} |
} |
||
return accum [].asSet() for v => ==maxCount in counts { _.with(v) } |
return accum [].asSet() for v => ==maxCount in counts { _.with(v) } |
||
}</ |
}</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]) |
||
# value: [4, 0].asSet()</ |
# 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 |
||
counts[v] := newCount |
counts[v] := newCount |
||
maxCount := maxCount.max(newCount)</ |
maxCount := maxCount.max(newCount)</syntaxhighlight> |
||
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. |
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}}== |
=={{header|EchoLisp}}== |
||
< |
<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 879: | Line 879: | ||
(modes '()) |
(modes '()) |
||
😖️ error: group : expected list : null 🔎 'modes' |
😖️ error: group : expected list : null 🔎 'modes' |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 5.0: |
ELENA 5.0: |
||
< |
<syntaxhighlight lang=elena>import system'routines; |
||
import system'collections; |
import system'collections; |
||
import extensions; |
import extensions; |
||
Line 919: | Line 919: | ||
.printLine("mode of (",array3.asEnumerable(),") is (",array3.Mode,")") |
.printLine("mode of (",array3.asEnumerable(),") is (",array3.Mode,")") |
||
.readChar() |
.readChar() |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 928: | Line 928: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<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 941: | Line 941: | ||
IO.puts "mode: #{inspect list}" |
IO.puts "mode: #{inspect list}" |
||
IO.puts " => #{inspect Average.mode(list)}" |
IO.puts " => #{inspect Average.mode(list)}" |
||
end)</ |
end)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 952: | Line 952: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang=Erlang> |
||
-module( mode ). |
-module( mode ). |
||
-export( [example/0, values/1] ). |
-export( [example/0, values/1] ). |
||
Line 974: | Line 974: | ||
values_count( Value, Dict ) -> dict:update_counter( Value, 1, Dict ). |
values_count( Value, Dict ) -> dict:update_counter( Value, 1, Dict ). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 982: | Line 982: | ||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
< |
<syntaxhighlight lang=ERRE>PROGRAM MODE_AVG |
||
!$INTEGER |
!$INTEGER |
||
Line 1,042: | Line 1,042: | ||
CALC_MODE(B[],4->MODES$) |
CALC_MODE(B[],4->MODES$) |
||
PRINT(MODES$) |
PRINT(MODES$) |
||
END PROGRAM</ |
END PROGRAM</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,050: | Line 1,050: | ||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang=euphoria>include misc.e |
||
function mode(sequence s) |
function mode(sequence s) |
||
Line 1,088: | Line 1,088: | ||
constant s = { 1, "blue", 2, 7.5, 5, "green", "red", 5, 2, "blue", "white" } |
constant s = { 1, "blue", 2, 7.5, 5, "green", "red", 5, 2, "blue", "white" } |
||
pretty_print(1,mode(s),{3})</ |
pretty_print(1,mode(s),{3})</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>{ |
<pre>{ |
||
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) = |
||
l |
l |
||
|> Seq.countBy (fun item -> item) // Count individual items |
|> Seq.countBy (fun item -> item) // Count individual items |
||
Line 1,107: | Line 1,107: | ||
else (cp,lst)) // else just keep old count/list |
else (cp,lst)) // else just keep old count/list |
||
(0, [Unchecked.defaultof<'a>]) // Start with a count of 0 and a dummy item |
(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)</ |
|> 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"];; |
||
val it : string list = ["c"] |
val it : string list = ["c"] |
||
> mode ["a"; "b"; "c"; "c";"a"];; |
> mode ["a"; "b"; "c"; "c";"a"];; |
||
val it : string list = ["c"; "a"] |
val it : string list = ["c"; "a"] |
||
> mode [1;2;1;3;2;0;0];; |
> mode [1;2;1;3;2;0;0];; |
||
val it : int list = [0; 2; 1]</ |
val it : int list = [0; 2; 1]</syntaxhighlight> |
||
=={{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> |
||
=={{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 |
||
use Qsort_Module only Qsort => sort |
use Qsort_Module only Qsort => sort |
||
implicit none |
implicit none |
||
Line 1,220: | Line 1,220: | ||
end function stat_mode |
end function stat_mode |
||
end program mode_test</ |
end program mode_test</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<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,288: | Line 1,288: | ||
Print |
Print |
||
Print "Press any key to quit" |
Print "Press any key to quit" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,298: | Line 1,298: | ||
=={{header|Frink}}== |
=={{header|Frink}}== |
||
< |
<syntaxhighlight lang=frink>modes[vals] := |
||
{ |
{ |
||
count = countToArray[vals] |
count = countToArray[vals] |
||
Line 1,314: | Line 1,314: | ||
println[modes[[1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]]] |
println[modes[[1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]]] |
||
println[modes[[1, 1, 2, 4, 4]]]</ |
println[modes[[1, 1, 2, 4, 4]]]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
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> |
||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang=gap>mode := function(v) |
||
local c, m; |
local c, m; |
||
c := Collected(SortedList(v)); |
c := Collected(SortedList(v)); |
||
Line 1,332: | Line 1,332: | ||
mode([ 7, 5, 6, 1, 5, 5, 7, 12, 17, 6, 6, 5, 12, 3, 6 ]); |
mode([ 7, 5, 6, 1, 5, 5, 7, 12, 17, 6, 6, 5, 12, 3, 6 ]); |
||
# [ 5, 6 ]</ |
# [ 5, 6 ]</syntaxhighlight> |
||
=={{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 |
||
import "fmt" |
import "fmt" |
||
Line 1,363: | Line 1,363: | ||
} |
} |
||
return mode |
return mode |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
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 |
||
import "fmt" |
import "fmt" |
||
Line 1,397: | Line 1,397: | ||
} |
} |
||
return mode |
return mode |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
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 |
||
import "fmt" |
import "fmt" |
||
Line 1,460: | Line 1,460: | ||
} |
} |
||
return mode |
return mode |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
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 |
||
import "fmt" |
import "fmt" |
||
Line 1,533: | Line 1,533: | ||
} |
} |
||
return mode |
return mode |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
("Enzyklopädie" has no repeated letters. All are modal.) |
("Enzyklopädie" has no repeated letters. All are modal.) |
||
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) { |
||
assert col |
assert col |
||
def m = [:] |
def m = [:] |
||
Line 1,551: | Line 1,551: | ||
def keys = m.keySet().sort { -m[it] } |
def keys = m.keySet().sort { -m[it] } |
||
keys.findAll { m[it] == m[keys[0]] } |
keys.findAll { m[it] == m[keys[0]] } |
||
}</ |
}</syntaxhighlight> |
||
Test: |
Test: |
||
< |
<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 { |
||
def a = (0..10).collect { sourceList[random.nextInt(5)] } |
def a = (0..10).collect { sourceList[random.nextInt(5)] } |
||
println "${mode(a)} == mode(${a})" |
println "${mode(a)} == mode(${a})" |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{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]) |
<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: | Line 1,573: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang=haskell>import Prelude (foldr, maximum, (==), (+)) |
||
import Data.Map (insertWith', empty, filter, elems, keys) |
import Data.Map (insertWith', empty, filter, elems, keys) |
||
mode :: (Ord a) => [a] -> [a] |
mode :: (Ord a) => [a] -> [a] |
||
mode xs = keys (filter (== maximum (elems counts)) counts) |
mode xs = keys (filter (== maximum (elems counts)) counts) |
||
where counts = foldr (\x -> insertWith' (+) x 1) empty xs</ |
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. |
''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] |
> mode [1,2,3,3,2,1,1] |
||
Line 1,585: | Line 1,585: | ||
[1,2,3] |
[1,2,3] |
||
Alternately: |
Alternately: |
||
< |
<syntaxhighlight lang=haskell>import Data.List (group, sort) |
||
mode :: (Ord a) => [a] -> [a] |
mode :: (Ord a) => [a] -> [a] |
||
mode xs = map fst $ filter ((==best).snd) counts |
mode xs = map fst $ filter ((==best).snd) counts |
||
where counts = map (\l -> (head l, length l)) . group . sort $ xs |
where counts = map (\l -> (head l, length l)) . group . sort $ xs |
||
best = maximum (map snd counts)</ |
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) |
||
mode :: (Eq a) => [a] -> [a] |
mode :: (Eq a) => [a] -> [a] |
||
Line 1,602: | Line 1,602: | ||
| otherwise = (best, x:modes) |
| otherwise = (best, x:modes) |
||
where (xs, notxs) = partition (== x) l |
where (xs, notxs) = partition (== x) l |
||
(best, modes) = modesWithCount notxs</ |
(best, modes) = modesWithCount notxs</syntaxhighlight> |
||
=={{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) |
||
every write(!mode(args)) |
every write(!mode(args)) |
||
end |
end |
||
Line 1,619: | Line 1,619: | ||
else fail |
else fail |
||
} |
} |
||
end</ |
end</syntaxhighlight> |
||
{{out|Sample outputs}} |
{{out|Sample outputs}} |
||
<pre>->am 3 1 4 1 5 9 7 6 |
<pre>->am 3 1 4 1 5 9 7 6 |
||
Line 1,629: | Line 1,629: | ||
=={{header|J}}== |
=={{header|J}}== |
||
< |
<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.*; |
||
public class Mode { |
public class Mode { |
||
Line 1,670: | Line 1,670: | ||
System.out.println(mode(Arrays.asList(1, 1, 2, 4, 4))); // prints [1, 4] |
System.out.println(mode(Arrays.asList(1, 1, 2, 4, 4))); // prints [1, 4] |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
< |
<syntaxhighlight lang=javascript>function mode(ary) { |
||
var counter = {}; |
var counter = {}; |
||
var mode = []; |
var mode = []; |
||
Line 1,693: | Line 1,693: | ||
mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]); // [6] |
mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]); // [6] |
||
mode([1, 2, 4, 4, 1]); // [1,4]</ |
mode([1, 2, 4, 4, 1]); // [1,4]</syntaxhighlight> |
||
=={{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.< |
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;</ |
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 |
||
[1.1, 1.2, 1.3, 1.1, 1.2, 1.1] | mode) # => 1.1</ |
[1.1, 1.2, 1.3, 1.1, 1.2, 1.1] | mode) # => 1.1</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<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,749: | Line 1,749: | ||
println(modes([1,3,6,6,6,6,7,7,12,12,17])) |
println(modes([1,3,6,6,6,6,7,7,12,12,17])) |
||
println(modes((1,1,2,4,4)))</ |
println(modes((1,1,2,4,4)))</syntaxhighlight> |
||
=={{header|K}}== |
=={{header|K}}== |
||
< |
<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</ |
3 4</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<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,777: | Line 1,777: | ||
println("[" + b.joinToString(", ") + "]") |
println("[" + b.joinToString(", ") + "]") |
||
modeOf(b) |
modeOf(b) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,789: | Line 1,789: | ||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<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,800: | Line 1,800: | ||
} |
} |
||
getmode(array(1,3,6,6,6,6,7,7,12,12,17)) |
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))</ |
getmode(array(1,3,6,3,4,8,9,1,2,3,2,2))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
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> |
|||
<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,866: | Line 1,866: | ||
modes$ = modes$; oldVal; " " |
modes$ = modes$; oldVal; " " |
||
end select |
end select |
||
end function </ |
end function </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,877: | Line 1,877: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<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,904: | Line 1,904: | ||
for _, val in pairs(modes) do io.write(val..' ') end |
for _, val in pairs(modes) do io.write(val..' ') end |
||
print("occur(s) ", count, " times") |
print("occur(s) ", count, " times") |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
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> |
||
Module Checkit { |
Module Checkit { |
||
\\ find mode |
\\ find mode |
||
Line 1,956: | Line 1,956: | ||
} |
} |
||
Checkit |
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. |
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: | Line 1,962: | ||
< |
<syntaxhighlight lang=M2000 Interpreter> |
||
Module Checkit { |
Module Checkit { |
||
Function GetMode(&a()){ |
Function GetMode(&a()){ |
||
Line 2,009: | Line 2,009: | ||
} |
} |
||
Checkit |
Checkit |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
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]); |
||
Statistics:-Mode([1, 2.1, 2.1, 3.2, 3.2, 5]);</ |
Statistics:-Mode([1, 2.1, 2.1, 3.2, 3.2, 5]);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
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}] |
||
Commonest[{1, 3, 2, 3}]</ |
Commonest[{1, 3, 2, 3}]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> {b,a,2} |
<pre> {b,a,2} |
||
Line 2,031: | Line 2,031: | ||
=={{header|MATLAB}}== |
=={{header|MATLAB}}== |
||
< |
<syntaxhighlight lang=Matlab>function modeValue = findmode(setOfValues) |
||
modeValue = mode(setOfValues); |
modeValue = mode(setOfValues); |
||
end</ |
end</syntaxhighlight> |
||
=={{header|MUMPS}}== |
=={{header|MUMPS}}== |
||
< |
<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,050: | Line 2,050: | ||
SET I="",I=$O(Y(I)),ML=I ;Prime the pump, rather than test for no data |
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) |
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</ |
QUIT ML</syntaxhighlight> |
||
<pre>USER>W $$MODE^ROSETTA("1^2^3^2") |
<pre>USER>W $$MODE^ROSETTA("1^2^3^2") |
||
2 |
2 |
||
Line 2,059: | Line 2,059: | ||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang=NetRexx>/* NetRexx */ |
||
options replace format comments java crossref symbols nobinary |
options replace format comments java crossref symbols nobinary |
||
Line 2,134: | Line 2,134: | ||
show_mode([Rexx 1, 1, 2, 4, 4]) -- 4 1 |
show_mode([Rexx 1, 1, 2, 4, 4]) -- 4 1 |
||
return |
return |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Output:''' |
'''Output:''' |
||
<pre> |
<pre> |
||
Line 2,157: | Line 2,157: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang=nim>import tables |
||
proc modes[T](xs: openArray[T]): T = |
proc modes[T](xs: openArray[T]): T = |
||
Line 2,166: | Line 2,166: | ||
echo modes(@[1,3,6,6,6,6,7,7,12,12,17]) |
echo modes(@[1,3,6,6,6,6,7,7,12,12,17]) |
||
echo modes(@[1,1,2,4,4])</ |
echo modes(@[1,1,2,4,4])</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>6 |
<pre>6 |
||
Line 2,173: | Line 2,173: | ||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |
||
{{Works with|oo2c version2}} |
{{Works with|oo2c version2}} |
||
< |
<syntaxhighlight lang=oberon2> |
||
MODULE Mode; |
MODULE Mode; |
||
IMPORT |
IMPORT |
||
Line 2,250: | Line 2,250: | ||
Show(Mode(z));Out.Ln; |
Show(Mode(z));Out.Ln; |
||
END Mode. |
END Mode. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out} |
{{out} |
||
<pre> |
<pre> |
||
Line 2,262: | Line 2,262: | ||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang=objeck> |
||
use Collection; |
use Collection; |
||
Line 2,313: | Line 2,313: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
< |
<syntaxhighlight lang=objc>#import <Foundation/Foundation.h> |
||
@interface NSArray (Mode) |
@interface NSArray (Mode) |
||
Line 2,339: | Line 2,339: | ||
return maxElems; |
return maxElems; |
||
} |
} |
||
@end</ |
@end</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<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,354: | Line 2,354: | ||
if v = best then k :: acc |
if v = best then k :: acc |
||
else acc) |
else acc) |
||
seen []</ |
seen []</syntaxhighlight> |
||
# mode [1;3;6;6;6;6;7;7;12;12;17];; |
# mode [1;3;6;6;6;6;7;7;12;12;17];; |
||
- : int list = [6] |
- : int list = [6] |
||
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) |
||
sv = sort(v); |
sv = sort(v); |
||
% build two vectors, vals and c, so that |
% build two vectors, vals and c, so that |
||
Line 2,390: | Line 2,390: | ||
i++; |
i++; |
||
endwhile |
endwhile |
||
endfunction</ |
endfunction</syntaxhighlight> |
||
< |
<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,397: | Line 2,397: | ||
a = [1, 1, 2, 4, 4]; |
a = [1, 1, 2, 4, 4]; |
||
mode2(a) % returns 1 and 4 |
mode2(a) % returns 1 and 4 |
||
mode(a) % returns 1 only</ |
mode(a) % returns 1 only</syntaxhighlight> |
||
=={{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> |
||
-- 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,434: | Line 2,434: | ||
return mode |
return mode |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<syntaxhighlight lang=oz>declare |
||
fun {Mode Xs} |
fun {Mode Xs} |
||
Freq = {Dictionary.new} |
Freq = {Dictionary.new} |
||
Line 2,453: | Line 2,453: | ||
in |
in |
||
{Show {Mode [1 2 3 3 2 1 1]}} |
{Show {Mode [1 2 3 3 2 1 1]}} |
||
{Show {Mode [1 2 3 3 2 1]}}</ |
{Show {Mode [1 2 3 3 2 1]}}</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<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,471: | Line 2,471: | ||
); |
); |
||
if(count>r,v[#v],b) |
if(count>r,v[#v],b) |
||
};</ |
};</syntaxhighlight> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang=perl>use strict; |
||
use List::Util qw(max); |
use List::Util qw(max); |
||
Line 2,485: | Line 2,485: | ||
my $best = max(values %c); |
my $best = max(values %c); |
||
return grep { $c{$_} == $best } keys %c; |
return grep { $c{$_} == $best } keys %c; |
||
}</ |
}</syntaxhighlight> |
||
< |
<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); |
||
print "\n";</ |
print "\n";</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<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,533: | 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: #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> |
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
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 |
||
function mode($arr) { |
function mode($arr) { |
||
$count = array_count_values($arr); |
$count = array_count_values($arr); |
||
Line 2,556: | Line 2,556: | ||
print_r(mode(array(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17))); |
print_r(mode(array(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17))); |
||
print_r(mode(array(1, 1, 2, 4, 4))); |
print_r(mode(array(1, 1, 2, 4, 4))); |
||
?></ |
?></syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang=PicoLisp>(de modes (Lst) |
||
(let A NIL |
(let A NIL |
||
(for X Lst |
(for X Lst |
||
Line 2,565: | Line 2,565: | ||
(mapcar car |
(mapcar car |
||
(maxi cdar |
(maxi cdar |
||
(by cdr group A) ) ) ) )</ |
(by cdr group A) ) ) ) )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>: (modes (1 3 6 6 6 6 7 7 12 12 17)) |
<pre>: (modes (1 3 6 6 6 6 7 7 12 12 17)) |
||
Line 2,580: | Line 2,580: | ||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<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,599: | Line 2,599: | ||
max || ' times.'); |
max || ' times.'); |
||
end av;</ |
end av;</syntaxhighlight> |
||
Results: |
Results: |
||
<pre> |
<pre> |
||
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) |
||
$groups = $data | group-object | sort-object count -Descending |
$groups = $data | group-object | sort-object count -Descending |
||
$groups | ? {$_.Count -eq $groups[0].Count}</ |
$groups | ? {$_.Count -eq $groups[0].Count}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Count Name Group |
<pre>Count Name Group |
||
Line 2,616: | Line 2,616: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang=PureBasic>Procedure mean(Array InArray(1)) |
||
Structure MyMean |
Structure MyMean |
||
Line 2,653: | Line 2,653: | ||
EndIf |
EndIf |
||
Next |
Next |
||
EndProcedure</ |
EndProcedure</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
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 |
||
>>> def modes(values): |
>>> def modes(values): |
||
count = defaultdict(int) |
count = defaultdict(int) |
||
Line 2,669: | Line 2,669: | ||
[6] |
[6] |
||
>>> modes((1,1,2,4,4)) |
>>> modes((1,1,2,4,4)) |
||
[1, 4]</ |
[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 |
||
>>> def modes(values): |
>>> def modes(values): |
||
count = Counter(values) |
count = Counter(values) |
||
Line 2,680: | Line 2,680: | ||
[6] |
[6] |
||
>>> modes((1,1,2,4,4)) |
>>> modes((1,1,2,4,4)) |
||
[1, 4]</ |
[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): |
||
return max(set(values), key=values.count)</ |
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> |
||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang=Quackery> [ sort |
||
[] [] rot |
[] [] rot |
||
dup 0 peek temp put |
dup 0 peek temp put |
||
Line 2,721: | Line 2,721: | ||
' [ 1 3 5 7 3 1 3 7 7 3 3 ] mode echo cr |
' [ 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 |
' [ 7 13 5 13 7 2 7 10 13 ] mode echo cr |
||
' [ 5 ] mode echo cr</ |
' [ 5 ] mode echo cr</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,731: | Line 2,731: | ||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang=R>statmode <- function(v) { |
||
a <- sort(table(v), decreasing=TRUE) |
a <- sort(table(v), decreasing=TRUE) |
||
r <- c() |
r <- c() |
||
Line 2,744: | Line 2,744: | ||
print(statmode(c(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17))) |
print(statmode(c(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17))) |
||
print(statmode(c(1, 1, 2, 4, 4)))</ |
print(statmode(c(1, 1, 2, 4, 4)))</syntaxhighlight> |
||
=={{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 |
||
(define (mode seq) |
(define (mode seq) |
||
Line 2,765: | Line 2,765: | ||
(values (cons k ms) freq)] |
(values (cons k ms) freq)] |
||
[else |
[else |
||
(values ms freq)])))</ |
(values ms freq)])))</syntaxhighlight> |
||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 2,771: | Line 2,771: | ||
{{works with|Rakudo|2019.03.1}} |
{{works with|Rakudo|2019.03.1}} |
||
< |
<syntaxhighlight lang=perl6>sub mode (*@a) { |
||
my %counts := @a.Bag; |
my %counts := @a.Bag; |
||
my $max = %counts.values.max; |
my $max = %counts.values.max; |
||
Line 2,779: | Line 2,779: | ||
# Testing with arrays: |
# Testing with arrays: |
||
say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]; |
say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]; |
||
say mode [1, 1, 2, 4, 4];</ |
say mode [1, 1, 2, 4, 4];</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
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) { |
||
@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,797: | Line 2,797: | ||
say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]; |
say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]; |
||
say mode [1, 1, 2, 4, 4];</ |
say mode [1, 1, 2, 4, 4];</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
===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. */ |
||
/* ════════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,827: | Line 2,827: | ||
end |
end |
||
end /*j*/ |
end /*j*/ |
||
return ? /*return the mode of vector to invoker.*/</ |
return ? /*return the mode of vector to invoker.*/</syntaxhighlight> |
||
'''output''' |
'''output''' |
||
<pre> |
<pre> |
||
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 */ |
||
/*-- ~~ main ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ |
/*-- ~~ main ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ |
||
call run_samples |
call run_samples |
||
Line 2,939: | Line 2,939: | ||
call show_mode '1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17' -- 6 |
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 |
call show_mode '1, 1, 2, 4, 4' -- 4 1 |
||
return</ |
return</syntaxhighlight> |
||
{{out}} |
{{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] |
<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: | Line 2,960: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang=ring> |
||
# Project : Averages/Mode |
# Project : Averages/Mode |
||
Line 3,003: | Line 3,003: | ||
next |
next |
||
return j |
return j |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
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) |
||
seen = Hash.new(0) |
seen = Hash.new(0) |
||
ary.each {|value| seen[value] += 1} |
ary.each {|value| seen[value] += 1} |
||
Line 3,040: | Line 3,040: | ||
p mode([1, 1, 2, 4, 4]) # => [1, 4] |
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, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]) # => [6] |
||
p mode_one_pass([1, 1, 2, 4, 4]) # => [1, 4]</ |
p mode_one_pass([1, 1, 2, 4, 4]) # => [1, 4]</syntaxhighlight> |
||
{{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) |
||
ary.max_by { |x| ary.count(x) } |
ary.max_by { |x| ary.count(x) } |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang=rust>use std::collections::HashMap; |
||
fn main() { |
fn main() { |
||
Line 3,079: | Line 3,079: | ||
vec_mode |
vec_mode |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
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; |
||
define find_max(key) { |
define find_max(key) { |
||
Line 3,127: | Line 3,127: | ||
find_mode({"Hungadunga", "Hungadunga", "Hungadunga", "Hungadunga", "McCormick"}); |
find_mode({"Hungadunga", "Hungadunga", "Hungadunga", "Hungadunga", "McCormick"}); |
||
find_mode({"foo", "2.3", "bar", "foo", "foobar", "quality", 2.3, "strnen"});</ |
find_mode({"foo", "2.3", "bar", "foo", "foobar", "quality", 2.3, "strnen"});</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Hungadunga has the most entries (4). |
<pre>Hungadunga has the most entries (4). |
||
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 |
||
import scala.collection.generic.CanBuildFrom |
import scala.collection.generic.CanBuildFrom |
||
def mode |
def mode |
||
Line 3,144: | Line 3,144: | ||
val max = grouped.map(_._2).max |
val max = grouped.map(_._2).max |
||
grouped.filter(_._2 == max).map(_._1)(breakOut) |
grouped.filter(_._2 == max).map(_._1)(breakOut) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
{{works with|Berkeley Scheme}} |
{{works with|Berkeley Scheme}} |
||
< |
<syntaxhighlight lang=scheme>(define (mode collection) |
||
(define (helper collection counts) |
(define (helper collection counts) |
||
(if (null? collection) |
(if (null? collection) |
||
Line 3,157: | Line 3,157: | ||
(map car |
(map car |
||
(filter (lambda (x) (= (cdr x) (apply max (map cdr (helper collection '()))))) |
(filter (lambda (x) (= (cdr x) (apply max (map cdr (helper collection '()))))) |
||
(helper collection '())))</ |
(helper collection '())))</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
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"; |
||
const proc: createModeFunction (in type: elemType) is func |
const proc: createModeFunction (in type: elemType) is func |
||
Line 3,217: | Line 3,217: | ||
writeln(mode([] (1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17))); |
writeln(mode([] (1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17))); |
||
writeln(mode([] (1, 1, 2, 4, 4))); |
writeln(mode([] (1, 1, 2, 4, 4))); |
||
end func;</ |
end func;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,226: | Line 3,226: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<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 ++}; |
||
var max = c.values.max; |
var max = c.values.max; |
||
c.keys.grep{|i| c{i} == max}; |
c.keys.grep{|i| c{i} == max}; |
||
}</ |
}</syntaxhighlight> |
||
'''Calling the function''' |
'''Calling the function''' |
||
< |
<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(' ');</ |
say mode([1, 1, 2, 4, 4]).join(' ');</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
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) { |
||
arr.max_by{|i| arr.count(i)}; |
arr.max_by{|i| arr.count(i)}; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang=Slate>s@(Sequence traits) mode |
||
[| sortedCounts | |
[| sortedCounts | |
||
sortedCounts: (s as: Bag) sortedCounts. |
sortedCounts: (s as: Bag) sortedCounts. |
||
(sortedCounts mapSelect: [| :count :elem | sortedCounts last count = count]) valueSet |
(sortedCounts mapSelect: [| :count :elem | sortedCounts last count = count]) valueSet |
||
].</ |
].</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
{{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 [ |
||
mode [ |s| |
mode [ |s| |
||
s := self asBag sortedByCount. |
s := self asBag sortedByCount. |
||
Line 3,269: | Line 3,269: | ||
mode displayNl. |
mode displayNl. |
||
#( 1 1 2 4 4) asOrderedCollection |
#( 1 1 2 4 4) asOrderedCollection |
||
mode displayNl.</ |
mode displayNl.</syntaxhighlight> |
||
=={{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.< |
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,305: | Line 3,305: | ||
counts |
counts |
||
where |
where |
||
num in (select max(num) from counts);</ |
num in (select max(num) from counts);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> MODE_VAL |
<pre> MODE_VAL |
||
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> |
||
// 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,346: | Line 3,346: | ||
emptyArray.mode() // returns nil |
emptyArray.mode() // returns nil |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{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 |
||
proc mode {n args} { |
proc mode {n args} { |
||
foreach n [list $n {*}$args] { |
foreach n [list $n {*}$args] { |
||
Line 3,367: | Line 3,367: | ||
# Testing |
# Testing |
||
puts [mode 1 3 6 6 6 6 7 7 12 12 17]; # --> 6 |
puts [mode 1 3 6 6 6 6 7 7 12 12 17]; # --> 6 |
||
puts [mode 1 1 2 4 4]; # --> 1 4</ |
puts [mode 1 1 2 4 4]; # --> 1 4</syntaxhighlight> |
||
Note that this works for any kind of value. |
Note that this works for any kind of value. |
||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
{{works with|bash|4.0}} |
{{works with|bash|4.0}} |
||
< |
<syntaxhighlight lang=bash>#!/bin/bash |
||
function mode { |
function mode { |
||
Line 3,386: | Line 3,386: | ||
done |
done |
||
echo |
echo |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang=bash>mode 1 2 1 2 a b a b a 2 |
||
a 2</ |
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 |
||
mode = ~&hS+ leql$^&h+ eql|=@K2 |
mode = ~&hS+ leql$^&h+ eql|=@K2 |
||
Line 3,398: | Line 3,398: | ||
#cast %nLW |
#cast %nLW |
||
examples = mode~~ (<1,3,6,6,6,7,7,12,12,17>,<1,1,2,4,4>)</ |
examples = mode~~ (<1,3,6,6,6,7,7,12,12,17>,<1,1,2,4,4>)</syntaxhighlight> |
||
The function is tested on a pair of lists, one with a unique mode and one with multiple modes. |
The function is tested on a pair of lists, one with a unique mode and one with multiple modes. |
||
{{out}} |
{{out}} |
||
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() |
||
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,411: | Line 3,411: | ||
Debug.Print x; |
Debug.Print x; |
||
Next x |
Next x |
||
End Sub</ |
End Sub</syntaxhighlight>{{out}} |
||
<pre> 3 4</pre> |
<pre> 3 4</pre> |
||
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 |
||
Reg_Copy(10, ALL) |
Reg_Copy(10, ALL) |
||
Buf_Switch(Buf_Free) |
Buf_Switch(Buf_Free) |
||
Line 3,445: | Line 3,445: | ||
Reg_Copy_Block(10, CP, EOL_pos) |
Reg_Copy_Block(10, CP, EOL_pos) |
||
Buf_Quit(OK) |
Buf_Quit(OK) |
||
Statline_Message(@10)</ |
Statline_Message(@10)</syntaxhighlight> |
||
=={{header|Vlang}}== |
=={{header|Vlang}}== |
||
< |
<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,473: | Line 3,473: | ||
} |
} |
||
return mode |
return mode |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[2] |
<pre>[2] |
||
Line 3,479: | Line 3,479: | ||
</pre> |
</pre> |
||
Or using `math.stats` module |
Or using `math.stats` module |
||
< |
<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])) |
||
println(stats.mode<int>([2, 7, 1, 8, 2, 8])) |
println(stats.mode<int>([2, 7, 1, 8, 2, 8])) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>2 |
<pre>2 |
||
Line 3,490: | Line 3,490: | ||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang=ecmascript>class Arithmetic { |
||
static mode(arr) { |
static mode(arr) { |
||
var map = {} |
var map = {} |
||
Line 3,502: | Line 3,502: | ||
} |
} |
||
System.print(Arithmetic.mode([1,2,3,4,5,5,51,2,3]))</ |
System.print(Arithmetic.mode([1,2,3,4,5,5,51,2,3]))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[2, 3, 5] |
[2, 3, 5] |
||
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) |
||
"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,527: | Line 3,527: | ||
(when (eq count mode-count) |
(when (eq count mode-count) |
||
(push value modes)))) |
(push value modes)))) |
||
modes))</ |
modes))</syntaxhighlight> |
||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
< |
<syntaxhighlight lang=Yabasic>sub floor(x) |
||
return int(x + .05) |
return int(x + .05) |
||
end sub |
end sub |
||
Line 3,595: | Line 3,595: | ||
result$ = getMode$("a, a, b, d, d") |
result$ = getMode$("a, a, b, d, d") |
||
print "mode ", left$(result$, n - 1), " occur(s) ", right$(result$, len(result$) - n), " times."</ |
print "mode ", left$(result$, n - 1), " occur(s) ", right$(result$, len(result$) - n), " times."</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
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){ |
||
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 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))); |
||
println("Mode: ", mode("this is a test".split("")));</ |
println("Mode: ", mode("this is a test".split("")));</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |