Averages/Mode: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1:
{{task|Probability and statistics}}
 
;Task
{{task heading}}
 
Write a program to find the [[wp:Mode (statistics)|mode]] value of a collection.
Line 17:
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">F modes(values)
DefaultDict[Int, Int] count
L(v) values
Line 33:
 
=={{header|Action!}}==
<syntaxhighlight lang=Action"action!">DEFINE MAX="100"
INT ARRAY keys(MAX)
INT ARRAY values(MAX)
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.
<syntaxhighlight lang=ActionScript"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 174:
{{works with|Ada 2005}}
mode.ads:
<syntaxhighlight lang=Ada"ada">generic
type Element_Type is private;
type Element_Array is array (Positive range <>) of Element_Type;
Line 183:
end Mode;</syntaxhighlight>
mode.adb:
<syntaxhighlight lang=Ada"ada">with Ada.Containers.Indefinite_Vectors;
 
package body Mode is
Line 286:
end Mode;</syntaxhighlight>
example use:
<syntaxhighlight lang=Ada"ada">with Ada.Text_IO;
with Mode;
procedure Main is
Line 317:
 
=={{header|APL}}==
<syntaxhighlight lang=APL"apl">mode←{{s←⌈/⍵[;2]⋄⊃¨(↓⍵)∩{⍵,s}¨⍵[;1]}{⍺,≢⍵}⌸⍵}</syntaxhighlight>
 
=={{header|AppleScript}}==
Line 323:
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
 
Line 377:
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">getMode: function [arr][
freqs: new #[]
loop arr 'i [
Line 399:
{{AutoHotkey case}}
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("0.1 2.2 -0.1 0.22e1 2.20 0.1")
Line 417:
=={{header|AWK}}==
<syntaxhighlight lang=AWK"awk">#!/usr/bin/gawk -f
{
# compute histogram
Line 466:
 
=={{header|BBC BASIC}}==
<syntaxhighlight 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 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.
<syntaxhighlight lang=C"c">#include <stdio.h>
#include <stdlib.h>
 
Line 584:
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.Collections;
using System.Collections.Generic;
Line 626:
=={{header|C++}}==
{{works with|g++|4.3.2}}
<syntaxhighlight lang="cpp">#include <iterator>
#include <utility>
#include <algorithm>
Line 698:
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">(defn modes [coll]
(let [distrib (frequencies coll)
[value freq] [first second] ; name the key/value pairs in the distrib (map) entries
Line 705:
(map value (take-while #(= maxfq (freq %)) sorted))))</syntaxhighlight>
Or a one-liner solution
<syntaxhighlight lang="clojure">(defn modes [coll]
(->> coll frequencies (sort-by val >) (partition-by val) first (map key)))</syntaxhighlight>
 
=={{header|CoffeeScript}}==
<syntaxhighlight lang="coffeescript">mode = (arr) ->
# returns an array with the modes of arr, i.e. the
# elements that appear most often in arr
Line 725:
=={{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.
<syntaxhighlight lang="lisp">(defun mode (sequence &rest hash-table-options)
(let ((frequencies (apply #'make-hash-table hash-table-options)))
(map nil (lambda (element)
Line 743:
=={{header|D}}==
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*/ {
Line 766:
{{libheader| System.Generics.Collections}}
{{libheader| System.Generics.Defaults}}
<syntaxhighlight lang=Delphi"delphi">
program AveragesMode;
 
Line 844:
Value: 12, Count: 4</pre>
=={{header|E}}==
<syntaxhighlight lang="e">pragma.enable("accumulator")
def mode(values) {
def counts := [].asMap().diverge()
Line 853:
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()</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:
<syntaxhighlight lang="e"> def newCount := counts.fetch(v, fn { 0 }) + 1
counts[v] := newCount
maxCount := maxCount.max(newCount)</syntaxhighlight>
Line 862:
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
(define (modes L)
(define G (group* L)) ;; sorts and group equal items
Line 883:
=={{header|Elena}}==
ELENA 5.0:
<syntaxhighlight lang="elena">import system'routines;
import system'collections;
import extensions;
Line 928:
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">defmodule Average do
def mode(list) do
gb = Enum.group_by(list, &(&1))
Line 952:
 
=={{header|Erlang}}==
<syntaxhighlight lang=Erlang"erlang">
-module( mode ).
-export( [example/0, values/1] ).
Line 982:
 
=={{header|ERRE}}==
<syntaxhighlight lang=ERRE"erre">PROGRAM MODE_AVG
 
!$INTEGER
Line 1,050:
 
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">include misc.e
 
function mode(sequence s)
Line 1,098:
=={{header|F_Sharp|F#}}==
The Unchecked.defaultof became available in version 1.9.4 I think.
<syntaxhighlight lang="fsharp">let mode (l:'a seq) =
l
|> Seq.countBy (fun item -> item) // Count individual items
Line 1,109:
|> snd // From (count, list) we just want the second item (the list)</syntaxhighlight>
Example usage:
<syntaxhighlight lang="fsharp">> mode ["a"; "b"; "c"; "c"];;
val it : string list = ["c"]
> mode ["a"; "b"; "c"; "c";"a"];;
Line 1,118:
=={{header|Factor}}==
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}}==
{{works with|Fortran|90 and later}}
For the <tt>Qsort_Module</tt> see [[Sorting_algorithms/Quicksort#Fortran]]
<syntaxhighlight lang="fortran">program mode_test
use Qsort_Module only Qsort => sort
implicit none
Line 1,223:
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub quicksort(a() As Integer, first As Integer, last As Integer)
Line 1,298:
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">modes[vals] :=
{
count = countToArray[vals]
Line 1,321:
</pre>
As of the 2022-07-31 release of Frink, the function can be rewritten as:
<syntaxhighlight lang="frink">modes[vals] := mostCommon[vals]@0</syntaxhighlight>
 
=={{header|GAP}}==
<syntaxhighlight lang="gap">mode := function(v)
local c, m;
c := Collected(SortedList(v));
Line 1,336:
=={{header|Go}}==
'''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"
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.
<syntaxhighlight lang="go">package main
 
import "fmt"
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.
<syntaxhighlight lang="go">package main
 
import "fmt"
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.
<syntaxhighlight lang="go">package main
 
import "fmt"
Line 1,543:
=={{header|Groovy}}==
Solution, both "collection type" and "element type" agnostic:
<syntaxhighlight lang="groovy">def mode(Iterable col) {
assert col
def m = [:]
Line 1,553:
}</syntaxhighlight>
Test:
<syntaxhighlight lang="groovy">def random = new Random()
def sourceList = [ 'Lamp', 42.0, java.awt.Color.RED, new Date(), ~/pattern/]
(0..10).each {
Line 1,573:
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">import Prelude (foldr, maximum, (==), (+))
import Data.Map (insertWith', empty, filter, elems, keys)
 
Line 1,585:
[1,2,3]
Alternately:
<syntaxhighlight lang="haskell">import Data.List (group, sort)
 
mode :: (Ord a) => [a] -> [a]
Line 1,592:
best = maximum (map snd counts)</syntaxhighlight>
Another version that does not require an orderable type:
<syntaxhighlight lang="haskell">import Data.List (partition)
 
mode :: (Eq a) => [a] -> [a]
Line 1,606:
=={{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.
<syntaxhighlight lang="icon">procedure main(args)
every write(!mode(args))
end
Line 1,629:
 
=={{header|J}}==
<syntaxhighlight lang="j">mode=: ~. #~ ( = >./ )@( #/.~ )</syntaxhighlight>
 
Literally: select from the unique values the values which appear the most often.
Line 1,643:
 
=={{header|Java}}==
<syntaxhighlight lang="java">import java.util.*;
 
public class Mode {
Line 1,673:
 
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">function mode(ary) {
var counter = {};
var mode = [];
Line 1,697:
=={{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.<syntaxhighlight 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;</syntaxhighlight>Examples:<syntaxhighlight lang="jq">
[1,2,3,1,2,1] | mode # => 1
[1,2,3,1,2,1,2] | mode # => 1 2
Line 1,721:
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">function modes(values)
dict = Dict() # Values => Number of repetitions
modesArray = typeof(values[1])[] # Array of the modes so far
Line 1,752:
 
=={{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
3 4</syntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight 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,789:
 
=={{header|Lasso}}==
<syntaxhighlight lang=Lasso"lasso">define getmode(a::array)::array => {
local(mmap = map, maxv = 0, modes = array)
// store counts
Line 1,808:
=={{header|Liberty BASIC}}==
Using string of integers instead collection.
<syntaxhighlight lang="lb">
a$ = "1 3 6 6 6 6 7 7 12 12 17"
b$ = "1 2 4 4 1"
Line 1,877:
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">function mode(tbl) -- returns table of modes and count
assert(type(tbl) == 'table')
local counts = { }
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).
 
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
Module Checkit {
\\ find mode
Line 1,962:
 
 
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
Module Checkit {
Function GetMode(&a()){
Line 2,014:
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:
<syntaxhighlight lang=Maple"maple">Statistics:-Mode([1, 2.1, 2.1, 3]);
Statistics:-Mode([1, 2.1, 2.1, 3.2, 3.2, 5]);</syntaxhighlight>
 
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:
<syntaxhighlight lang=Mathematica"mathematica"> Commonest[{b, a, c, 2, a, b, 1, 2, 3}]
Commonest[{1, 3, 2, 3}]</syntaxhighlight>
{{out}}
Line 2,031:
 
=={{header|MATLAB}}==
<syntaxhighlight lang=Matlab"matlab">function modeValue = findmode(setOfValues)
modeValue = mode(setOfValues);
end</syntaxhighlight>
 
=={{header|MUMPS}}==
<syntaxhighlight lang=MUMPS"mumps">MODE(X)
;X is assumed to be a list of numbers separated by "^"
;I is a loop index
Line 2,059:
 
=={{header|NetRexx}}==
<syntaxhighlight lang=NetRexx"netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,157:
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import tables
 
proc modes[T](xs: openArray[T]): T =
Line 2,173:
=={{header|Oberon-2}}==
{{Works with|oo2c version2}}
<syntaxhighlight lang="oberon2">
MODULE Mode;
IMPORT
Line 2,262:
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">
use Collection;
 
Line 2,316:
 
=={{header|Objective-C}}==
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>
@interface NSArray (Mode)
Line 2,342:
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let mode lst =
let seen = Hashtbl.create 42 in
List.iter (fun x ->
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.
<syntaxhighlight lang="octave">function m = mode2(v)
sv = sort(v);
% build two vectors, vals and c, so that
Line 2,391:
endwhile
endfunction</syntaxhighlight>
<syntaxhighlight lang="octave">a = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
mode2(a)
mode(a)
Line 2,401:
=={{header|ooRexx}}==
See the example at [[#Version_2|REXX, Version 2]] for a version that returns multiple mode values.
<syntaxhighlight lang=ooRexx"oorexx">
-- will work with just about any collection...
call testMode .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
Line 2,437:
 
=={{header|Oz}}==
<syntaxhighlight lang="oz">declare
fun {Mode Xs}
Freq = {Dictionary.new}
Line 2,456:
 
=={{header|PARI/GP}}==
<syntaxhighlight lang="parigp">mode(v)={
my(count=1,r=1,b=v[1]);
v=vecsort(v);
Line 2,474:
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">use strict;
use List::Util qw(max);
 
Line 2,487:
}</syntaxhighlight>
 
<syntaxhighlight 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);
Line 2,493:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix"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,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.
<syntaxhighlight lang="php"><?php
function mode($arr) {
$count = array_count_values($arr);
Line 2,559:
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">(de modes (Lst)
(let A NIL
(for X Lst
Line 2,580:
 
=={{header|PL/I}}==
<syntaxhighlight lang=PL"pl/Ii">av: procedure options (main); /* 28 October 2013 */
declare x(10) fixed binary static initial (1, 4, 2, 6, 2, 5, 6, 2, 4, 2);
declare f(32767) fixed binary;
Line 2,606:
 
=={{header|PowerShell}}==
<syntaxhighlight lang=PowerShell"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}</syntaxhighlight>
Line 2,616:
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">Procedure mean(Array InArray(1))
 
Structure MyMean
Line 2,658:
The following solutions require that the elements be ''hashable''.
{{works with|Python|2.5+ and 3.x}}
<syntaxhighlight lang="python">>>> from collections import defaultdict
>>> def modes(values):
count = defaultdict(int)
Line 2,671:
[1, 4]</syntaxhighlight>
{{works with|Python|2.7+ and 3.1+}}
<syntaxhighlight lang="python">>>> from collections import Counter
>>> def modes(values):
count = Counter(values)
Line 2,682:
[1, 4]</syntaxhighlight>
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)</syntaxhighlight>
 
=={{header|Q}}==
<syntaxhighlight lang="q">mode:{(key x) where value x=max x} count each group @</syntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang=Quackery"quackery"> [ sort
[] [] rot
dup 0 peek temp put
Line 2,731:
 
=={{header|R}}==
<syntaxhighlight lang=R"r">statmode <- function(v) {
a <- sort(table(v), decreasing=TRUE)
r <- c()
Line 2,748:
=={{header|Racket}}==
Returns values of list of modes and their frequencies of appearance.
<syntaxhighlight lang=Racket"racket">#lang racket
 
(define (mode seq)
Line 2,771:
 
{{works with|Rakudo|2019.03.1}}
<syntaxhighlight lang=perl6"raku" line>sub mode (*@a) {
my %counts := @a.Bag;
my $max = %counts.values.max;
Line 2,789:
Alternatively, a version that uses a single method chain with no temporary variables: (Same output with same input)
 
<syntaxhighlight lang=perl6"raku" line>sub mode (*@a) {
@a.Bag # count elements
.classify(*.value) # group elements with the same count
Line 2,802:
===version 1===
Returns one mode value.
<syntaxhighlight 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,848:
{{works with|Regina}}
and should work for every REXX.
<syntaxhighlight lang=REXX"rexx">/* Rexx */
/*-- ~~ main ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
call run_samples
Line 2,960:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Averages/Mode
 
Line 3,014:
=={{header|Ruby}}==
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)
ary.each {|value| seen[value] += 1}
Line 3,043:
{{works with|Ruby|1.8.7}}
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) }
end</syntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">use std::collections::HashMap;
 
fn main() {
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.
<syntaxhighlight lang=S"s-lang">private variable mx, mxkey, modedat;
 
define find_max(key) {
Line 3,135:
{{works with|Scala|2.8}}
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
def mode
Line 3,148:
=={{header|Scheme}}==
{{works with|Berkeley Scheme}}
<syntaxhighlight lang="scheme">(define (mode collection)
(define (helper collection counts)
(if (null? collection)
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.
 
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: createModeFunction (in type: elemType) is func
Line 3,226:
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">func mode(array) {
var c = Hash.new;
array.each{|i| c{i} := 0 ++};
Line 3,234:
 
'''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(' ');</syntaxhighlight>
 
Line 3,245:
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)};
}</syntaxhighlight>
 
=={{header|Slate}}==
<syntaxhighlight lang=Slate"slate">s@(Sequence traits) mode
[| sortedCounts |
sortedCounts: (s as: Bag) sortedCounts.
Line 3,259:
{{works with|GNU Smalltalk}}
This code is able to find the mode of any collection of any kind of object.
<syntaxhighlight lang="smalltalk">OrderedCollection extend [
mode [ |s|
s := self asBag sortedByCount.
Line 3,272:
 
=={{header|SQL}}==
Some databases have a built-in function. In Oracle you can say <code>select stats_mode(val) from...</code> but that returns one value, so doesn't handle non-unique modes. Other databases don't have a built-in. So here's a way to do this in a query.<syntaxhighlight lang="sql">-- setup
create table averages (val integer);
insert into averages values (1);
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.
 
<syntaxhighlight lang=Swift"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,350:
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<syntaxhighlight lang="tcl"># Can find the modal value of any vector of values
proc mode {n args} {
foreach n [list $n {*}$args] {
Line 3,372:
=={{header|UNIX Shell}}==
{{works with|bash|4.0}}
<syntaxhighlight lang="bash">#!/bin/bash
 
function mode {
Line 3,387:
echo
}</syntaxhighlight>
<syntaxhighlight lang="bash">mode 1 2 1 2 a b a b a 2
a 2</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang=Ursala"ursala">#import std
 
mode = ~&hS+ leql$^&h+ eql|=@K2
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.
<syntaxhighlight lang="vb">Public Sub main()
s = [{1,2,3,3,3,4,4,4,5,5,6}]
t = WorksheetFunction.Mode_Mult(s)
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.
<syntaxhighlight lang="vedit">BOF // Copy all data to a new buffer
Reg_Copy(10, ALL)
Buf_Switch(Buf_Free)
Line 3,448:
 
=={{header|Vlang}}==
<syntaxhighlight lang="vlang">fn main() {
println(mode([2, 7, 1, 8, 2]))
println(mode([2, 7, 1, 8, 2, 8]))
Line 3,479:
</pre>
Or using `math.stats` module
<syntaxhighlight lang="vlang">import math.stats
fn main() {
println(stats.mode<int>([2, 7, 1, 8, 2]))
Line 3,490:
 
=={{header|Wren}}==
<syntaxhighlight lang="ecmascript">class Arithmetic {
static mode(arr) {
var map = {}
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.
<syntaxhighlight lang="xelisp">(defun mode ( predicate &rest values)
"Finds the mode of all values passed in.
Uses `predicate' to compare items."
Line 3,530:
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">sub floor(x)
return int(x + .05)
end sub
Line 3,605:
This is a bit funky in that modes are returned as strings.
{{trans|D}}
<syntaxhighlight 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);
}</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.append(2)));
10,327

edits