Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Averages/Mode
note: Probability and statistics

View file

@ -0,0 +1,14 @@
;Task
Write a program to find the [[wp:Mode (statistics)|mode]] value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
{{task heading|See also}}
{{Related tasks/Statistical measures}}
<hr>

View file

@ -0,0 +1,9 @@
F modes(values)
DefaultDict[Int, Int] count
L(v) values
count[v]++
V best = max(count.values())
R count.filter(kv -> kv[1] == @best).map(kv -> kv[0])
print(modes([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]))
print(modes([1, 1, 2, 4, 4]))

View file

@ -0,0 +1,63 @@
BEGIN # find the mode (most frequent value) of a set of items #
PR read "rows.incl.a68" PR # include row (array) utilities #
# returns the mode(s) of a - similar operators could be defined for #
# types other than INT #
OP MODEOF = ( []INT a )[]INT:
IF LWB a > UPB a THEN []INT() # no data #
ELSE # have data #
[ LWB a : UPB a ]INT sorted data := a;
QUICKSORT sorted data FROMELEMENT LWB sorted data TOELEMENT UPB sorted data;
INT distinct count = BEGIN # count the number of distinct values #
INT count := 1;
INT value := sorted data[ LWB sorted data ];
FOR i FROM LWB sorted data + 1 TO UPB sorted data DO
IF value /= sorted data[ i ] THEN
count +:= 1;
value := sorted data[ i ]
FI
OD;
count
END;
INT current value := sorted data[ LWB sorted data ];
INT max count := 0;
INT current count := 1;
INT s pos := LWB sorted data + 1;
# allow for the maximum possible number of modes #
[ 1 : distinct count ]INT modes;
INT mode count := 1;
modes[ 1 ] := current value;
WHILE s pos <= UPB sorted data DO
s pos +:= 1;
WHILE IF s pos > UPB sorted data
THEN FALSE
ELSE sorted data[ s pos ] = current value
FI
DO
current count +:= 1;
s pos +:= 1
OD;
IF current count > max count THEN
max count := current count;
modes[ mode count := 1 ] := sorted data[ s pos - 1 ]
ELIF current count = max count THEN
modes[ mode count +:= 1 ] := sorted data[ s pos - 1 ]
FI;
current count := 0;
IF s pos <= UPB sorted data THEN
current value := sorted data[ s pos ]
FI
OD;
modes[ 1 : mode count ]
FI # MODEOF # ;
# test cases as in the 11l sample #
SHOW MODEOF []INT( 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17 );print( ( newline ) );
SHOW MODEOF []INT( 1, 1, 2, 4, 4 ) ;print( ( newline ) );
# test cases as in the Action! sample #
SHOW MODEOF []INT( 1, 3, 5, 7, 3, 1, 3, 7, 7, 3, 3 ) ;print( ( newline ) );
SHOW MODEOF []INT( 7, 13, 5, 13, 7, 2, 7, 10, 13 ) ;print( ( newline ) );
SHOW MODEOF []INT( 5 ) ;print( ( newline ) );
# additional test case #
SHOW MODEOF []INT( 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 ) ;print( ( newline )
END

View file

@ -0,0 +1 @@
mode{{s/[;2]¨(){,s}¨[;1]}{,}}

View file

@ -0,0 +1,30 @@
#!/usr/bin/gawk -f
{
# compute histogram
histo[$1] += 1;
};
function mode(HIS) {
# Computes the mode from Histogram A
max = 0;
n = 0;
for (k in HIS) {
val = HIS[k];
if (HIS[k] > max) {
max = HIS[k];
n = 1;
List[n] = k;
} else if (HIS[k] == max) {
List[++n] = k;
}
}
for (k=1; k<=n; k++) {
o = o""OFS""List[k];
}
return o;
}
END {
print mode(histo);
};

View file

@ -0,0 +1,88 @@
DEFINE MAX="100"
INT ARRAY keys(MAX)
INT ARRAY values(MAX)
BYTE count
PROC PrintArray(INT ARRAY a INT size)
INT i
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
PROC ClearMap()
count=0
RETURN
PROC AddToMap(INT a)
INT i,index
index=-1
IF count>0 THEN
FOR i=0 TO count-1
DO
IF keys(i)=a THEN
index=i EXIT
FI
OD
FI
IF index=-1 THEN
keys(count)=a
values(count)=1
count==+1
ELSE
values(index)==+1
FI
RETURN
PROC Mode(INT ARRAY a INT aSize INT ARRAY m INT POINTER mSize)
INT i,mx
ClearMap()
FOR i=0 TO aSize-1
DO
AddToMap(a(i))
OD
mx=0
FOR i=0 TO count-1
DO
IF values(i)>mx THEN
mx=values(i)
FI
OD
mSize^=0
FOR i=0 TO count-1
DO
IF values(i)=mx THEN
m(mSize^)=keys(i)
mSize^==+1
FI
OD
RETURN
PROC Test(INT ARRAY a INT size)
INT ARRAY m(MAX)
INT mSize
PrintE("Array:") PrintArray(a,size)
Mode(a,size,m,@mSize)
PrintE("Mode:") PrintArray(m,mSize)
PutE()
RETURN
PROC Main()
INT ARRAY a=[1 3 5 7 3 1 3 7 7 3 3]
INT ARRAY b=[7 13 5 13 7 2 7 10 13]
INT ARRAY c=[5]
Test(a,11)
Test(b,9)
Test(c,1)
RETURN

View file

@ -0,0 +1,28 @@
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.
var count:Array = new Array();
var modeList:Array;
var maxCount:uint=0;
for (var i:String in arr) {
//Record how many times an element has occurred. Note that each element in the cuont array
//has to be initialized explicitly, since it is an associative array.
if (count[arr[i]]==undefined) {
count[arr[i]]=1;
} else {
count[arr[i]]++;
}
//If this is now the most common element, clear the list of modes, and add this element.
if(count[arr[i]] > maxCount)
{
maxCount=count[arr[i]];
modeList = new Array();
modeList.push(arr[i]);
}
//If this is a mode, add it to the list.
else if(count[arr[i]] == maxCount){
modeList.push(arr[i]);
}
}
return modeList;
}

View file

@ -0,0 +1,8 @@
generic
type Element_Type is private;
type Element_Array is array (Positive range <>) of Element_Type;
package Mode is
function Get_Mode (Set : Element_Array) return Element_Array;
end Mode;

View file

@ -0,0 +1,102 @@
with Ada.Containers.Indefinite_Vectors;
package body Mode is
-- map Count to Elements
package Count_Vectors is new Ada.Containers.Indefinite_Vectors
(Element_Type => Element_Array,
Index_Type => Positive);
procedure Add (To : in out Count_Vectors.Vector; Item : Element_Type) is
use type Count_Vectors.Cursor;
Position : Count_Vectors.Cursor := To.First;
Found : Boolean := False;
begin
while not Found and then Position /= Count_Vectors.No_Element loop
declare
Elements : Element_Array := Count_Vectors.Element (Position);
begin
for I in Elements'Range loop
if Elements (I) = Item then
Found := True;
end if;
end loop;
end;
if not Found then
Position := Count_Vectors.Next (Position);
end if;
end loop;
if Position /= Count_Vectors.No_Element then
-- element found, remove it and insert to next count
declare
New_Position : Count_Vectors.Cursor :=
Count_Vectors.Next (Position);
begin
-- remove from old position
declare
Old_Elements : Element_Array :=
Count_Vectors.Element (Position);
New_Elements : Element_Array (1 .. Old_Elements'Length - 1);
New_Index : Positive := New_Elements'First;
begin
for I in Old_Elements'Range loop
if Old_Elements (I) /= Item then
New_Elements (New_Index) := Old_Elements (I);
New_Index := New_Index + 1;
end if;
end loop;
To.Replace_Element (Position, New_Elements);
end;
-- new position not already there?
if New_Position = Count_Vectors.No_Element then
declare
New_Array : Element_Array (1 .. 1) := (1 => Item);
begin
To.Append (New_Array);
end;
else
-- add to new position
declare
Old_Elements : Element_Array :=
Count_Vectors.Element (New_Position);
New_Elements : Element_Array (1 .. Old_Elements'Length + 1);
begin
New_Elements (1 .. Old_Elements'Length) := Old_Elements;
New_Elements (New_Elements'Last) := Item;
To.Replace_Element (New_Position, New_Elements);
end;
end if;
end;
else
-- element not found, add to count 1
Position := To.First;
if Position = Count_Vectors.No_Element then
declare
New_Array : Element_Array (1 .. 1) := (1 => Item);
begin
To.Append (New_Array);
end;
else
declare
Old_Elements : Element_Array :=
Count_Vectors.Element (Position);
New_Elements : Element_Array (1 .. Old_Elements'Length + 1);
begin
New_Elements (1 .. Old_Elements'Length) := Old_Elements;
New_Elements (New_Elements'Last) := Item;
To.Replace_Element (Position, New_Elements);
end;
end if;
end if;
end Add;
function Get_Mode (Set : Element_Array) return Element_Array is
Counts : Count_Vectors.Vector;
begin
for I in Set'Range loop
Add (Counts, Set (I));
end loop;
return Counts.Last_Element;
end Get_Mode;
end Mode;

View file

@ -0,0 +1,26 @@
with Ada.Text_IO;
with Mode;
procedure Main is
type Int_Array is array (Positive range <>) of Integer;
package Int_Mode is new Mode (Integer, Int_Array);
Test_1 : Int_Array := (1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6);
Result : Int_Array := Int_Mode.Get_Mode (Test_1);
begin
Ada.Text_IO.Put ("Input: ");
for I in Test_1'Range loop
Ada.Text_IO.Put (Integer'Image (Test_1 (I)));
if I /= Test_1'Last then
Ada.Text_IO.Put (",");
end if;
end loop;
Ada.Text_IO.New_Line;
Ada.Text_IO.Put ("Result:");
for I in Result'Range loop
Ada.Text_IO.Put (Integer'Image (Result (I)));
if I /= Result'Last then
Ada.Text_IO.Put (",");
end if;
end loop;
Ada.Text_IO.New_Line;
end Main;

View file

@ -0,0 +1,51 @@
use AppleScript version "2.3.1" -- Mac OS X 10.9 (Mavericks) or later (for these 'use' commands).
use sorter : script "Shell sort" -- https://www.rosettacode.org/wiki/Sorting_algorithms/Shell_sort#AppleScript
on modeOf(listOrRecord)
-- Extract and sort numbers and text separately, then concatenate the results to get a single list of values.
set theNumbers to listOrRecord's numbers
tell sorter to sort(theNumbers, 1, -1)
set theTexts to listOrRecord's text
tell sorter to sort(theTexts, 1, -1)
script o
property values : theNumbers & theTexts
property mode : {}
end script
-- Identify the most frequently occurring value(s).
if (o's values is not {}) then
set i to 1
set currentValue to beginning of o's values
set maxCount to 1
repeat with j from 2 to (count o's values)
set thisValue to item j of o's values
if (thisValue is not currentValue) then
set thisCount to j - i
if (thisCount > maxCount) then
set o's mode to {currentValue}
set maxCount to thisCount
else if (thisCount = maxCount) then
set end of o's mode to currentValue
end if
set i to j
set currentValue to thisValue
end if
end repeat
if (j + 1 - i > maxCount) then
set o's mode to {currentValue}
else if (j + 1 - i = maxCount) then
set end of o's mode to currentValue
end if
end if
return o's mode
end modeOf
-- Test code:
-- With a list:
modeOf({12, 4, "rhubarb", 88, "rhubarb", 17, "custard", 4.0, 4, 88, "rhubarb"})
--> {4, "rhubarb"}
-- With a record:
modeOf({a:12, b:4, c:"rhubarb", d:88, e:"rhubarb", f:17, g:"custard", h:4.0, i:4, j:88})
--> {4}

View file

@ -0,0 +1,13 @@
getMode: function [arr][
freqs: new #[]
loop arr 'i [
k: to :string i
if not? key? freqs k -> set freqs k 0
freqs\[k]: (freqs\[k]) + 1
]
maximum: max values freqs
select keys freqs 'i -> maximum = freqs\[i]
]
print getMode [1 3 6 6 6 6 7 7 12 12 17]
print getMode [1 1 2 4 4]

View file

@ -0,0 +1,15 @@
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")
Mode(a, d=" ") { ; the number that occurs most frequently in a list delimited by d (space)
Sort a, ND%d%
Loop Parse, a, %d%
If (V != A_LoopField) {
If (Ct > MxCt)
MxV := V, MxCt := Ct
V := A_LoopField, Ct := 1
}
Else Ct++
Return Ct>MxCt ? V : MxV
}

View file

@ -0,0 +1,33 @@
DIM a(10), b(4)
a() = 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17
b() = 1, 2, 4, 4, 1
DIM modes(10)
PRINT "Mode(s) of a() = " ;
FOR i% = 1 TO FNmodes(a(), modes())
PRINT ; modes(i%) " " ;
NEXT
PRINT
PRINT "Mode(s) of b() = " ;
FOR i% = 1 TO FNmodes(b(), modes())
PRINT ; modes(i%) " " ;
NEXT
PRINT
END
DEF FNmodes(a(), m())
LOCAL I%, J%, N%, c%(), max%
N% = DIM(a(),1)
IF N% = 0 THEN m(1) = a(0) : = 1
DIM c%(N%)
FOR I% = 0 TO N%-1
FOR J% = I%+1 TO N%
IF a(I%) = a(J%) c%(I%) += 1
NEXT
IF c%(I%) > max% max% = c%(I%)
NEXT I%
J% = 0
FOR I% = 0 TO N%
IF c%(I%) = max% J% += 1 : m(J%) = a(I%)
NEXT
= J%

View file

@ -0,0 +1,68 @@
#include <iterator>
#include <utility>
#include <algorithm>
#include <list>
#include <iostream>
// helper struct
template<typename T> struct referring
{
referring(T const& t): value(t) {}
template<typename Iter>
bool operator()(std::pair<Iter, int> const& p) const
{
return *p.first == value;
}
T const& value;
};
// requires:
// FwdIterator is a ForwardIterator
// The value_type of FwdIterator is EqualityComparable
// OutIterator is an output iterator
// the value_type of FwdIterator is convertible to the value_type of OutIterator
// [first, last) is a valid range
// provides:
// the mode is written to result
template<typename FwdIterator, typename OutIterator>
void mode(FwdIterator first, FwdIterator last, OutIterator result)
{
typedef typename std::iterator_traits<FwdIterator>::value_type value_type;
typedef std::list<std::pair<FwdIterator, int> > count_type;
typedef typename count_type::iterator count_iterator;
// count elements
count_type counts;
while (first != last)
{
count_iterator element = std::find_if(counts.begin(), counts.end(),
referring<value_type>(*first));
if (element == counts.end())
counts.push_back(std::make_pair(first, 1));
else
++element->second;
++first;
}
// find maximum
int max = 0;
for (count_iterator i = counts.begin(); i != counts.end(); ++i)
if (i->second > max)
max = i->second;
// copy corresponding elements to output sequence
for (count_iterator i = counts.begin(); i != counts.end(); ++i)
if (i->second == max)
*result++ = *i->first;
}
// example usage
int main()
{
int values[] = { 1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6 };
median(values, values + sizeof(values)/sizeof(int),
std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
return 0;
}

View file

@ -0,0 +1,38 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Test
{
class Program
{
static void Main(string[] args)
{
/*
* We Use Linq To Determine The Mode
*/
List<int> myList = new List<int>() { 1, 1, 2, 4, 4 };
var query = from numbers in myList //select the numbers
group numbers by numbers //group them together so we can get the count
into groupedNumbers
select new { Number = groupedNumbers.Key, Count = groupedNumbers.Count() }; //so we got a query
//find the max of the occurence of the mode
int max = query.Max(g => g.Count);
IEnumerable<int> modes = query.Where(x => x.Count == max).Select(x => x.Number);//match the frequence and select the number
foreach (var item in modes)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
}

View file

@ -0,0 +1,59 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct { double v; int c; } vcount;
int cmp_dbl(const void *a, const void *b)
{
double x = *(const double*)a - *(const double*)b;
return x < 0 ? -1 : x > 0;
}
int vc_cmp(const void *a, const void *b)
{
return ((const vcount*)b)->c - ((const vcount*)a)->c;
}
int get_mode(double* x, int len, vcount **list)
{
int i, j;
vcount *vc;
/* sort values */
qsort(x, len, sizeof(double), cmp_dbl);
/* count occurence of each value */
for (i = 0, j = 1; i < len - 1; i++, j += (x[i] != x[i + 1]));
*list = vc = malloc(sizeof(vcount) * j);
vc[0].v = x[0];
vc[0].c = 1;
/* generate list value-count pairs */
for (i = j = 0; i < len - 1; i++, vc[j].c++)
if (x[i] != x[i + 1]) vc[++j].v = x[i + 1];
/* sort that by count in descending order */
qsort(vc, j + 1, sizeof(vcount), vc_cmp);
/* the number of entries with same count as the highest */
for (i = 0; i <= j && vc[i].c == vc[0].c; i++);
return i;
}
int main()
{
double values[] = { 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 12, 12, 17 };
# define len sizeof(values)/sizeof(double)
vcount *vc;
int i, n_modes = get_mode(values, len, &vc);
printf("got %d modes:\n", n_modes);
for (i = 0; i < n_modes; i++)
printf("\tvalue = %g, count = %d\n", vc[i].v, vc[i].c);
free(vc);
return 0;
}

View file

@ -0,0 +1,6 @@
(defn modes [coll]
(let [distrib (frequencies coll)
[value freq] [first second] ; name the key/value pairs in the distrib (map) entries
sorted (sort-by (comp - freq) distrib)
maxfq (freq (first sorted))]
(map value (take-while #(= maxfq (freq %)) sorted))))

View file

@ -0,0 +1,2 @@
(defn modes [coll]
(->> coll frequencies (sort-by val >) (partition-by val) first (map key)))

View file

@ -0,0 +1,13 @@
mode = (arr) ->
# returns an array with the modes of arr, i.e. the
# elements that appear most often in arr
counts = {}
for elem in arr
counts[elem] ||= 0
counts[elem] += 1
max = 0
for key, cnt of counts
max = cnt if cnt > max
(key for key, cnt of counts when cnt == max)
console.log mode [1, 2, 2, 2, 3, 3, 3, 4, 4]

View file

@ -0,0 +1,15 @@
(defun mode (sequence &rest hash-table-options)
(let ((frequencies (apply #'make-hash-table hash-table-options)))
(map nil (lambda (element)
(incf (gethash element frequencies 0)))
sequence)
(let ((modes '())
(hifreq 0 ))
(maphash (lambda (element frequency)
(cond ((> frequency hifreq)
(setf hifreq frequency
modes (list element)))
((= frequency hifreq)
(push element modes))))
frequencies)
(values modes hifreq))))

View file

@ -0,0 +1,17 @@
import std.stdio, std.algorithm, std.array;
auto mode(T)(T[] items) pure /*nothrow @safe*/ {
int[T] aa;
foreach (item; items)
aa[item]++;
immutable m = aa.byValue.reduce!max;
return aa.byKey.filter!(k => aa[k] == m);
}
void main() /*@safe*/ {
auto data = [1, 2, 3, 1, 2, 4, 2, 5, 3, 3, 1, 3, 6];
writeln("Mode: ", data.mode);
data ~= 2;
writeln("Mode: ", data.mode);
}

View file

@ -0,0 +1,72 @@
program AveragesMode;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Generics.Collections,
System.Generics.Defaults;
type
TCounts = TDictionary<Integer, Integer>;
TPair = record
value, count: Integer;
constructor Create(value, count: Integer);
end;
TPairs = TArray<TPair>;
var
dict: TCounts;
Pairs: TPairs;
list: TArray<Integer>;
i, key, max: Integer;
p: TPair;
{ TPair }
constructor TPair.Create(value, count: Integer);
begin
self.value := value;
self.count := count;
end;
function SortByCount(const left, right: TPair): Integer;
begin
Result := right.count - left.count;
end;
begin
list := [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 12, 12, 17];
dict := TCounts.Create;
for i in list do
begin
if dict.ContainsKey(i) then
dict[i] := dict[i] + 1
else
begin
dict.Add(i, 1);
end;
end;
SetLength(Pairs, dict.Count);
i := 0;
for key in dict.Keys do
begin
Pairs[i] := TPair.Create(key, dict[key]);
inc(i);
end;
TArray.Sort<TPair>(Pairs, TComparer<TPair>.Construct(SortByCount));
Writeln('Modes:');
max := Pairs[0].count;
for p in Pairs do
if p.count = max then
Writeln(' Value: ', p.value, ', Count: ', p.count);
dict.Free;
Readln;
end.

View file

@ -0,0 +1,9 @@
pragma.enable("accumulator")
def mode(values) {
def counts := [].asMap().diverge()
var maxCount := 0
for v in values {
maxCount max= (counts[v] := counts.fetch(v, fn{0}) + 1)
}
return accum [].asSet() for v => ==maxCount in counts { _.with(v) }
}

View file

@ -0,0 +1,2 @@
? 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()

View file

@ -0,0 +1,3 @@
def newCount := counts.fetch(v, fn { 0 }) + 1
counts[v] := newCount
maxCount := maxCount.max(newCount)

View file

@ -0,0 +1,61 @@
PROGRAM MODE_AVG
!$INTEGER
DIM A[10],B[10],Z[10]
PROCEDURE SORT(Z[],P->Z[])
LOCAL N,FLIPS
FLIPS=TRUE
WHILE FLIPS DO
FLIPS=FALSE
FOR N=0 TO P-1 DO
IF Z[N]>Z[N+1] THEN SWAP(Z[N],Z[N+1]) FLIPS=TRUE
END FOR
END WHILE
END PROCEDURE
PROCEDURE CALC_MODE(Z[],P->MODES$)
LOCAL I,OCCURRENCE,MAXOCCURRENCE,OLDVAL
SORT(Z[],P->Z[])
OCCURENCE=1
MAXOCCURENCE=0
OLDVAL=Z[0]
MODES$=""
FOR I=1 TO P DO
IF Z[I]=OLDVAL THEN
OCCURENCE=OCCURENCE+1
ELSE
IF OCCURENCE>MAXOCCURENCE THEN
MAXOCCURENCE=OCCURENCE
MODES$=STR$(OLDVAL)
ELSIF OCCURENCE=MAXOCCURENCE THEN
MODES$=MODES$+STR$(OLDVAL)
ELSE
!$NULL
END IF
OCCURENCE=1
END IF
OLDVAL=Z[I]
END FOR
!check after loop
IF OCCURENCE>MAXOCCURENCE THEN
MAXOCCURENCE=OCCURENCE
MODES$=STR$(OLDVAL)
ELSIF OCCURENCE=MAXOCCURENCE THEN
MODES$=MODES$+STR$(OLDVAL)
ELSE
!$NULL
END IF
END PROCEDURE
BEGIN
A[]=(1,3,6,6,6,6,7,7,12,12,17)
B[]=(1,2,4,4,1)
PRINT("Modes for array A (1,3,6,6,6,6,7,7,12,12,17)";)
CALC_MODE(A[],10->MODES$)
PRINT(MODES$)
PRINT("Modes for array B (1,2,4,4,1)";)
CALC_MODE(B[],4->MODES$)
PRINT(MODES$)
END PROGRAM

View file

@ -0,0 +1,16 @@
(define (modes L)
(define G (group* L)) ;; sorts and group equal items
(define cardmax (for/max [(g G)] (length g)))
(map first (filter (lambda(g) (= cardmax (length g))) G)))
(modes '( a b c a d e f))
→ (a)
(modes (iota 6))
→ (0 1 2 3 4 5)
(modes '(x))
→ (x)
(modes '(🎾 🏉 ☕️ 🎾 🎲 🎯 🎺 ☕️ 🎲 🎸 🎻 🏆 ☕️ 🏁 🎾 🎲 🎻 🏉 ))
→ (🎾 ☕️ 🎲)
(modes '())
😖️ error: group : expected list : null 🔎 'modes'

View file

@ -0,0 +1,37 @@
import system'routines;
import system'collections;
import extensions;
extension op
{
get Mode()
{
var countMap := Dictionary.new(0);
self.forEach:(item)
{
countMap[item] := countMap[item] + 1
};
countMap := countMap.Values.sort:(p,n => p > n);
var max := countMap.FirstMember;
^ countMap
.filterBy:(kv => max.equal(kv.Value))
.selectBy:(kv => kv.Key)
.toArray()
}
}
public program()
{
var array1 := new int[]{1, 1, 2, 4, 4};
var array2 := new int[]{1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17};
var array3 := new object[]{1, "blue", 2, 7.5r, 5, "green", "red", 5, 2, "blue", "white"};
console
.printLine("mode of (",array1.asEnumerable(),") is (",array1.Mode,")")
.printLine("mode of (",array2.asEnumerable(),") is (",array2.Mode,")")
.printLine("mode of (",array3.asEnumerable(),") is (",array3.Mode,")")
.readChar()
}

View file

@ -0,0 +1,14 @@
defmodule Average do
def mode(list) do
gb = Enum.group_by(list, &(&1))
max = Enum.map(gb, fn {_,val} -> length(val) end) |> Enum.max
for {key,val} <- gb, length(val)==max, do: key
end
end
lists = [[3,1,4,1,5,9,2,6,5,3,5,8,9],
[1, 2, "qwe", "asd", 1, 2, "qwe", "asd", 2, "qwe"]]
Enum.each(lists, fn list ->
IO.puts "mode: #{inspect list}"
IO.puts " => #{inspect Average.mode(list)}"
end)

View file

@ -0,0 +1,21 @@
-module( mode ).
-export( [example/0, values/1] ).
example() ->
Set = [1, 2, "qwe", "asd", 1, 2, "qwe", "asd", 2, "qwe"],
io:fwrite( "In ~p the mode(s) is(are): ~p~n", [Set, values(Set)] ).
values( Set ) ->
Dict = lists:foldl( fun values_count/2, dict:new(), Set ),
[X || {X, _Y} <- dict:fold( fun keep_maxs/3, [{0, 0}], Dict )].
keep_maxs( Key, Value, [{_Max_key, Max_value} | _] ) when Value > Max_value ->
[{Key, Value}];
keep_maxs( Key, Value, [{_Max_key, Max_value} | _]=Maxs ) when Value =:= Max_value ->
[{Key, Value} | Maxs];
keep_maxs( _Key, _Value, Maxs ) ->
Maxs.
values_count( Value, Dict ) -> dict:update_counter( Value, 1, Dict ).

View file

@ -0,0 +1,39 @@
include misc.e
function mode(sequence s)
sequence uniques, counts, modes
integer j,max
uniques = {}
counts = {}
for i = 1 to length(s) do
j = find(s[i], uniques)
if j then
counts[j] += 1
else
uniques = append(uniques, s[i])
counts = append(counts, 1)
end if
end for
max = counts[1]
for i = 2 to length(counts) do
if counts[i] > max then
max = counts[i]
end if
end for
j = 1
modes = {}
while j <= length(s) do
j = find_from(max, counts, j)
if j = 0 then
exit
end if
modes = append(modes, uniques[j])
j += 1
end while
return modes
end function
constant s = { 1, "blue", 2, 7.5, 5, "green", "red", 5, 2, "blue", "white" }
pretty_print(1,mode(s),{3})

View file

@ -0,0 +1,10 @@
let mode (l:'a seq) =
l
|> Seq.countBy (fun item -> item) // Count individual items
|> Seq.fold // Find max counts
(fun (cp, lst) (item, c) -> // State is (count, list of items with that count)
if c > cp then (c, [item]) // New max - keep count and a list of the single item
elif c = cp then (c, item :: lst) // New element with max count - prepend it to the list
else (cp,lst)) // else just keep old count/list
(0, [Unchecked.defaultof<'a>]) // Start with a count of 0 and a dummy item
|> snd // From (count, list) we just want the second item (the list)

View file

@ -0,0 +1,6 @@
> mode ["a"; "b"; "c"; "c"];;
val it : string list = ["c"]
> mode ["a"; "b"; "c"; "c";"a"];;
val it : string list = ["c"; "a"]
> mode [1;2;1;3;2;0;0];;
val it : int list = [0; 2; 1]

View file

@ -0,0 +1 @@
{ 11 9 4 9 4 9 } mode ! 9

View file

@ -0,0 +1,98 @@
program mode_test
use Qsort_Module only Qsort => sort
implicit none
integer, parameter :: S = 10
integer, dimension(S) :: a1 = (/ -1, 7, 7, 2, 2, 2, -1, 7, -3, -3 /)
integer, dimension(S) :: a2 = (/ 1, 1, 1, 1, 1, 0, 2, 2, 2, 2 /)
integer, dimension(S) :: a3 = (/ 0, 0, -1, -1, 9, 9, 3, 3, 7, 7 /)
integer, dimension(S) :: o
integer :: l, trash
print *, stat_mode(a1)
trash = stat_mode(a1, o, l)
print *, o(1:l)
trash = stat_mode(a2, o, l)
print *, o(1:l)
trash = stat_mode(a3, o, l)
print *, o(1:l)
contains
! stat_mode returns the lowest (if not unique) mode
! others can hold other modes, if the mode is not unique
! if others is provided, otherslen should be provided too, and
! it says how many other modes are there.
! ok can be used to know if the return value has a meaning
! or the mode can't be found (void arrays)
integer function stat_mode(a, others, otherslen, ok)
integer, dimension(:), intent(in) :: a
logical, optional, intent(out) :: ok
integer, dimension(size(a,1)), optional, intent(out) :: others
integer, optional, intent(out) :: otherslen
! ta is a copy of a, we sort ta modifying it, freq
! holds the frequencies and idx the index (for ta) so that
! the value appearing freq(i)-time is ta(idx(i))
integer, dimension(size(a, 1)) :: ta, freq, idx
integer :: rs, i, tm, ml, tf
if ( present(ok) ) ok = .false.
select case ( size(a, 1) )
case (0) ! no mode... ok is false
return
case (1)
if ( present(ok) ) ok = .true.
stat_mode = a(1)
return
case default
if ( present(ok) ) ok = .true.
ta = a ! copy the array
call sort(ta) ! sort it in place (cfr. sort algos on RC)
freq = 1
idx = 0
rs = 1 ! rs will be the number of different values
do i = 2, size(ta, 1)
if ( ta(i-1) == ta(i) ) then
freq(rs) = freq(rs) + 1
else
idx(rs) = i-1
rs = rs + 1
end if
end do
idx(rs) = i-1
ml = maxloc(freq(1:rs), 1) ! index of the max value of freq
tf = freq(ml) ! the max frequency
tm = ta(idx(ml)) ! the value with that freq
! if we want all the possible modes, we provide others
if ( present(others) ) then
i = 1
others(1) = tm
do
freq(ml) = 0
ml = maxloc(freq(1:rs), 1)
if ( tf == freq(ml) ) then ! the same freq
i = i + 1 ! as the max one
others(i) = ta(idx(ml))
else
exit
end if
end do
if ( present(otherslen) ) then
otherslen = i
end if
end if
stat_mode = tm
end select
end function stat_mode
end program mode_test

View file

@ -0,0 +1,66 @@
' FB 1.05.0 Win64
Sub quicksort(a() As Integer, first As Integer, last As Integer)
Dim As Integer length = last - first + 1
If length < 2 Then Return
Dim pivot As Integer = a(first + length\ 2)
Dim lft As Integer = first
Dim rgt As Integer = last
While lft <= rgt
While a(lft) < pivot
lft +=1
Wend
While a(rgt) > pivot
rgt -= 1
Wend
If lft <= rgt Then
Swap a(lft), a(rgt)
lft += 1
rgt -= 1
End If
Wend
quicksort(a(), first, rgt)
quicksort(a(), lft, last)
End Sub
' The modal value(s) is/are stored in 'm'.
' The function returns the modal count.
Function mode(a() As Integer, m() As Integer, sorted As Boolean = false) As Integer
Dim lb As Integer = LBound(a)
Dim ub As Integer = UBound(a)
If ub = -1 Then Return 0 '' empty array
If Not sorted Then quicksort(a(), lb, ub)
Dim cValue As Integer = a(lb)
Dim cCount As Integer = 1
Dim cMax As Integer = 0
'' We iterate to the end of the array plus 1 to ensure the
'' final value is dealt with properly
For i As Integer = lb + 1 To ub + 1
If i <= ub AndAlso a(i) = cValue Then
cCount += 1
Else
If cCount > cMax Then
Erase m
Redim m(1 To 1)
m(1) = cValue
cMax = cCount
ElseIf cCount = cMax Then
Redim Preserve m(1 To UBound(m) + 1)
m(UBound(m)) = cValue
End If
If i = ub + 1 Then Exit For
cValue = a(i)
cCount = 1
End If
Next
Return cMax
End Function
Dim a(1 To 14) As Integer = {1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6}
Dim m() As Integer '' to store the mode(s)
Dim mCount As Integer = mode(a(), m())
Print "The following are the modes which occur"; mCount; " times : "
For i As Integer = LBound(m) To UBound(m) : Print m(i); " "; : Next
Print
Print "Press any key to quit"
Sleep

View file

@ -0,0 +1,17 @@
modes[vals] :=
{
count = countToArray[vals]
biggest = count@0@1
result = new array
for i = rangeOf[count]
if count@i@1 < biggest
break // count is sorted so we can bail out when numbers decrease
else
result.push[count@i@0]
return result
}
println[modes[[1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]]]
println[modes[[1, 1, 2, 4, 4]]]

View file

@ -0,0 +1 @@
modes[vals] := mostCommon[vals]@0

View file

@ -0,0 +1,9 @@
mode := function(v)
local c, m;
c := Collected(SortedList(v));
m := Maximum(List(c, x -> x[2]));
return List(Filtered(c, x -> x[2] = m), y -> y[1]);
end;
mode([ 7, 5, 6, 1, 5, 5, 7, 12, 17, 6, 6, 5, 12, 3, 6 ]);
# [ 5, 6 ]

View file

@ -0,0 +1,28 @@
package main
import "fmt"
func main() {
fmt.Println(mode([]int{2, 7, 1, 8, 2}))
fmt.Println(mode([]int{2, 7, 1, 8, 2, 8}))
}
func mode(a []int) []int {
m := make(map[int]int)
for _, v := range a {
m[v]++
}
var mode []int
var n int
for k, v := range m {
switch {
case v < n:
case v > n:
n = v
mode = append(mode[:0], k)
default:
mode = append(mode, k)
}
}
return mode
}

View file

@ -0,0 +1,28 @@
package main
import "fmt"
func main() {
fmt.Println(mode([]interface{}{.2, .7, .1, .8, .2}))
fmt.Println(mode([]interface{}{"two", 7, 1, 8, "two", 8}))
}
func mode(a []interface{}) []interface{} {
m := make(map[interface{}]int)
for _, v := range a {
m[v]++
}
var mode []interface{}
var n int
for k, v := range m {
switch {
case v < n:
case v > n:
n = v
mode = append(mode[:0], k)
default:
mode = append(mode, k)
}
}
return mode
}

View file

@ -0,0 +1,57 @@
package main
import "fmt"
// interface type
type intCollection interface {
iterator() func() (int, bool)
}
// concrete type implements interface
type intSlice []int
// method on concrete type satisfies interface method
func (s intSlice) iterator() func() (int, bool) {
i := 0
return func() (int, bool) {
if i >= len(s) {
return 0, false
}
v := s[i]
i++
return v, true
}
}
func main() {
fmt.Println(mode(intSlice{2, 7, 1, 8, 2}))
fmt.Println(mode(intSlice{2, 7, 1, 8, 2, 8}))
}
// mode is now a generic function, in a sense.
// It knows what to do with an intCollection,
// but does not know the underlying concrete type.
func mode(a intCollection) []int {
m := make(map[int]int)
i := a.iterator()
for {
v, ok := i()
if !ok {
break
}
m[v]++
}
var mode []int
var n int
for k, v := range m {
switch {
case v < n:
case v > n:
n = v
mode = append(mode[:0], k)
default:
mode = append(mode, k)
}
}
return mode
}

View file

@ -0,0 +1,67 @@
package main
import "fmt"
type collection interface {
iterator() func() (interface{}, bool)
}
type intSlice []int
func (s intSlice) iterator() func() (interface{}, bool) {
i := 0
return func() (interface{}, bool) {
if i >= len(s) {
return 0, false
}
v := s[i]
i++
return v, true
}
}
type runeList string
func (s runeList) iterator() func() (interface{}, bool) {
c := make(chan rune)
go func() {
for _, r := range s {
c <- r
}
close(c)
}()
return func() (interface{}, bool) {
r, ok := <-c
return string(r), ok
}
}
func main() {
fmt.Println(mode(intSlice{2, 7, 1, 8, 2}))
fmt.Println(mode(runeList("Enzyklopädie")))
}
func mode(a collection) []interface{} {
m := make(map[interface{}]int)
i := a.iterator()
for {
v, ok := i()
if !ok {
break
}
m[v]++
}
var mode []interface{}
var n int
for k, v := range m {
switch {
case v < n:
case v > n:
n = v
mode = append(mode[:0], k)
default:
mode = append(mode, k)
}
}
return mode
}

View file

@ -0,0 +1,9 @@
def mode(Iterable col) {
assert col
def m = [:]
col.each {
m[it] = m[it] == null ? 1 : m[it] + 1
}
def keys = m.keySet().sort { -m[it] }
keys.findAll { m[it] == m[keys[0]] }
}

View file

@ -0,0 +1,6 @@
def random = new Random()
def sourceList = [ 'Lamp', 42.0, java.awt.Color.RED, new Date(), ~/pattern/]
(0..10).each {
def a = (0..10).collect { sourceList[random.nextInt(5)] }
println "${mode(a)} == mode(${a})"
}

View file

@ -0,0 +1,6 @@
import Prelude (foldr, maximum, (==), (+))
import Data.Map (insertWith', empty, filter, elems, keys)
mode :: (Ord a) => [a] -> [a]
mode xs = keys (filter (== maximum (elems counts)) counts)
where counts = foldr (\x -> insertWith' (+) x 1) empty xs

View file

@ -0,0 +1,6 @@
import Data.List (group, sort)
mode :: (Ord a) => [a] -> [a]
mode xs = map fst $ filter ((==best).snd) counts
where counts = map (\l -> (head l, length l)) . group . sort $ xs
best = maximum (map snd counts)

View file

@ -0,0 +1,11 @@
import Data.List (partition)
mode :: (Eq a) => [a] -> [a]
mode = snd . modesWithCount
where modesWithCount :: (Eq a) => [a] -> (Int, [a])
modesWithCount [] = (0,[])
modesWithCount l@(x:_) | length xs > best = (length xs, [x])
| length xs < best = (best, modes)
| otherwise = (best, x:modes)
where (xs, notxs) = partition (== x) l
(best, modes) = modesWithCount notxs

View file

@ -0,0 +1,14 @@
procedure main(args)
every write(!mode(args))
end
procedure mode(A)
hist := table(0)
every hist[!A] +:= 1
hist := sort(hist, 2)
modeCnt := hist[*hist][2]
every modeP := hist[*hist to 1 by -1] do {
if modeCnt = modeP[2] then suspend modeP[1]
else fail
}
end

View file

@ -0,0 +1 @@
mode=: ~. #~ ( = >./ )@( #/.~ )

View file

@ -0,0 +1,45 @@
fn mode<T, U>(anon iterable: U) throws -> {T} {
mut dictionary = Dictionary<T, u64>()
for item in iterable {
if dictionary.contains(item) {
dictionary[item]++
} else {
dictionary[item] = 1
}
}
mut items = dictionary.iterator()
let mode = items.next()
if not mode.has_value() {
let empty_set: {T} = {}
return empty_set
}
mut modes = [mode.value()]
for item in items {
if item.1 > modes[0].1 {
modes = [item]
} else if item.1 == modes[0].1 {
modes.push(item)
}
}
mut mode_set: {T} = {}
for mode in modes {
mode_set.add(mode.0)
}
return mode_set
}
fn main() {
println("{}", mode<i64>([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]))
println("{}", mode<i64>([1, 1, 2, 4, 4]))
let empty_array: [i64] = []
println("{}", mode<i64>(empty_array))
let test_string = "abcabbcaca"
println("{}", mode<u32>(test_string.code_points()))
}

View file

@ -0,0 +1,28 @@
import java.util.*;
public class Mode {
public static <T> List<T> mode(List<? extends T> coll) {
Map<T, Integer> seen = new HashMap<T, Integer>();
int max = 0;
List<T> maxElems = new ArrayList<T>();
for (T value : coll) {
if (seen.containsKey(value))
seen.put(value, seen.get(value) + 1);
else
seen.put(value, 1);
if (seen.get(value) > max) {
max = seen.get(value);
maxElems.clear();
maxElems.add(value);
} else if (seen.get(value) == max) {
maxElems.add(value);
}
}
return maxElems;
}
public static void main(String[] args) {
System.out.println(mode(Arrays.asList(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17))); // prints [6]
System.out.println(mode(Arrays.asList(1, 1, 2, 4, 4))); // prints [1, 4]
}
}

View file

@ -0,0 +1,21 @@
function mode(ary) {
var counter = {};
var mode = [];
var max = 0;
for (var i in ary) {
if (!(ary[i] in counter))
counter[ary[i]] = 0;
counter[ary[i]]++;
if (counter[ary[i]] == max)
mode.push(ary[i]);
else if (counter[ary[i]] > max) {
max = counter[ary[i]];
mode = [ary[i]];
}
}
return mode;
}
mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]); // [6]
mode([1, 2, 4, 4, 1]); // [1,4]

View file

@ -0,0 +1,19 @@
# modes/0 produces an array of [value, count]
# in increasing order of count:
def modes:
sort | reduce .[] as $i ([];
# state variable is an array of [value, count]
if length == 0 then [ [$i, 1] ]
elif .[-1][0] == $i then setpath([-1,1]; .[-1][1] + 1)
else . + [[$i,1]]
end )
| sort_by( .[1] );
# mode/0 outputs a stream of the modal values;
# if the input array is empty, the output stream is also empty.
def mode:
if length == 0 then empty
else modes as $modes
| $modes[-1][1] as $count
| $modes[] | select( .[1] == $count) | .[0]
end;

View file

@ -0,0 +1,3 @@
[1,2,3,1,2,1] | mode # => 1
[1,2,3,1,2,1,2] | mode # => 1 2
[1.1, 1.2, 1.3, 1.1, 1.2, 1.1] | mode) # => 1.1

View file

@ -0,0 +1,29 @@
function modes(values)
dict = Dict() # Values => Number of repetitions
modesArray = typeof(values[1])[] # Array of the modes so far
max = 0 # Max of repetitions so far
for v in values
# Add one to the dict[v] entry (create one if none)
if v in keys(dict)
dict[v] += 1
else
dict[v] = 1
end
# Update modesArray if the number of repetitions
# of v reaches or surpasses the max value
if dict[v] >= max
if dict[v] > max
empty!(modesArray)
max += 1
end
append!(modesArray, [v])
end
end
return modesArray
end
println(modes([1,3,6,6,6,6,7,7,12,12,17]))
println(modes((1,1,2,4,4)))

View file

@ -0,0 +1,3 @@
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

View file

@ -0,0 +1,21 @@
fun <T> modeOf(a: Array<T>) {
val sortedByFreq = a.groupBy { it }.entries.sortedByDescending { it.value.size }
val maxFreq = sortedByFreq.first().value.size
val modes = sortedByFreq.takeWhile { it.value.size == maxFreq }
if (modes.size == 1)
println("The mode of the collection is ${modes.first().key} which has a frequency of $maxFreq")
else {
print("There are ${modes.size} modes with a frequency of $maxFreq, namely : ")
println(modes.map { it.key }.joinToString(", "))
}
}
fun main(args: Array<String>) {
val a = arrayOf(7, 1, 1, 6, 2, 4, 2, 4, 2, 1, 5)
println("[" + a.joinToString(", ") + "]")
modeOf(a)
println()
val b = arrayOf(true, false, true, false, true, true)
println("[" + b.joinToString(", ") + "]")
modeOf(b)
}

View file

@ -0,0 +1,12 @@
define getmode(a::array)::array => {
local(mmap = map, maxv = 0, modes = array)
// store counts
with e in #a do => { #mmap->keys >> #e ? #mmap->find(#e) += 1 | #mmap->insert(#e = 1) }
// get max value
with e in #mmap->keys do => { #mmap->find(#e) > #maxv ? #maxv = #mmap->find(#e) }
// get modes with max value
with e in #mmap->keys where #mmap->find(#e) == #maxv do => { #modes->insert(#e) }
return #modes
}
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))

View file

@ -0,0 +1,58 @@
a$ = "1 3 6 6 6 6 7 7 12 12 17"
b$ = "1 2 4 4 1"
print "Modes for ";a$
print modes$(a$)
print "Modes for ";b$
print modes$(b$)
function modes$(a$)
'get array size
n=0
t$ = "*"
while t$<>""
n=n+1
t$=word$(a$, n)
'print n, t$
wend
n=n-1
'print "n=", n
'dim array
'read in array
redim a(n)
for i = 1 to n
a(i)=val(word$(a$, i))
'print i, a(i)
next
'sort
sort a(), 1, n
'get the modes
occurence = 1
maxOccurence = 0
oldVal = a(1)
modes$ = ""
for i = 2 to n
'print i, a(i)
if a(i) = oldVal then
occurence = occurence + 1
else
select case
case occurence > maxOccurence
maxOccurence = occurence
modes$ = oldVal; " "
case occurence = maxOccurence
modes$ = modes$; oldVal; " "
end select
occurence = 1
end if
oldVal = a(i)
next
'check after loop
select case
case occurence > maxOccurence
maxOccurence = occurence
modes$ = oldVal; " "
case occurence = maxOccurence
modes$ = modes$; oldVal; " "
end select
end function

View file

@ -0,0 +1,27 @@
function mode(tbl) -- returns table of modes and count
assert(type(tbl) == 'table')
local counts = { }
for _, val in pairs(tbl) do
-- see http://lua-users.org/wiki/TernaryOperator
counts[val] = counts[val] and counts[val] + 1 or 1
end
local modes = { }
local modeCount = 0
for key, val in pairs(counts) do
if val > modeCount then
modeCount = val
modes = {key}
elseif val == modeCount then
table.insert(modes, key)
end
end
return modes, modeCount
end
modes, count = mode({1,3,6,6,6,6,7,7,12,12,17})
for _, val in pairs(modes) do io.write(val..' ') end
print("occur(s) ", count, " times")
modes, count = mode({'a', 'a', 'b', 'd', 'd'})
for _, val in pairs(modes) do io.write(val..' ') end
print("occur(s) ", count, " times")

View file

@ -0,0 +1,44 @@
Module Checkit {
\\ find mode
Function GetMode {
Inventory N
Inventory ALLMODES
m=1
While not empty {
if islet then {
Read A$
if Exist(N, A$) then {
k=Eval(N)
k++
if m=k then {
Append ALLMODES, A$
}
if m<k then m=k : Clear ALLMODES : Append ALLMODES, A$
return N, A$:=k
} Else Append N, A$:=1 : if m=1 then Append ALLMODES, A$
} else {
Read A
if Exist(N, A) then {
k=Eval(N)
k++
if m=k then {
Append ALLMODES, A
}
if m<k then m=k : Clear ALLMODES : Append ALLMODES, A
return N, A:=k
} Else Append N, A:=1 : if m=1 then Append ALLMODES, A
}
}
=ALLMODES
}
Print GetMode(1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6) ' print 2 3
Dim A()
A()=(1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6)
\\ get a pointer from A
m=A()
Print GetMode(!m) ' print 2 3
z=stack:=1, 2,"B", 3, 1, 2, "B", 4, 2, 5,"B", 2, 3, 3, 1, 3, 6, "B"
Print GetMode(!z) ' print 2 3 B
}
Checkit

View file

@ -0,0 +1,46 @@
Module Checkit {
Function GetMode(&a()){
Local max%
if len(a())=0 then =(,)
link a() to a$()
n%=len(a())
dim c%(n%)
if type$(a(0))="String" then {
For i%=0 to n%-2
For j%=i%+1 to n%-1
if order(a$(i%), a$(j%))=0 then c%(i%)++
Next j%
If c%(i%)>max% Then max%=c%(i%)
Next i%
For i%=0 to n%-1
If c%(i%) = max% Then Data a$(i%)
Next i%
} Else {
For i%=0 to n%-2
For j%=i%+1 to n%-1
if a(i%)==a(j%) then c%(i%)++
Next j%
If c%(i%)>max% Then max%=c%(i%)
Next i%
For i%=0 to n%-1
If c%(i%) = max% Then Data a(i%)
Next i%
}
=Array([])
}
Dim m()
m()=(2,3,43,234,234,3,324)
Print GetMode(&m()) ' 3 234
k=(1,2,1,2,1,2,3)
n=GetMode(&k)
' iterate backward
i=each(n, -1, 1)
While i {
Print Array(i),
}
Print
k=("A","B","A","B", "B","C","D","A")
? GetMode(&k) ' A B
}
Checkit

View file

@ -0,0 +1,3 @@
function modeValue = findmode(setOfValues)
modeValue = mode(setOfValues);
end

View file

@ -0,0 +1,15 @@
MODE(X)
;X is assumed to be a list of numbers separated by "^"
;I is a loop index
;L is the length of X
;Y is a new array
;ML is the list of modes
;LOC is a placeholder to shorten the statement
Q:'$DATA(X) "No data"
Q:X="" "Empty Set"
NEW Y,I,L,LOC
SET L=$LENGTH(X,"^"),ML=""
FOR I=1:1:L SET LOC=+$P(X,"^",I),Y(LOC)=$S($DATA(Y(LOC)):Y(LOC)+1,1:1)
SET I="",I=$O(Y(I)),ML=I ;Prime the pump, rather than test for no data
FOR S I=$O(Y(I)) Q:I="" S ML=$SELECT(Y($P(ML,"^"))>Y(I):ML,Y($P(ML,"^"))<Y(I):I,Y($P(ML,"^"))=Y(I):ML_"^"_I)
QUIT ML

View file

@ -0,0 +1,2 @@
Statistics:-Mode([1, 2.1, 2.1, 3]);
Statistics:-Mode([1, 2.1, 2.1, 3.2, 3.2, 5]);

View file

@ -0,0 +1,2 @@
Commonest[{b, a, c, 2, a, b, 1, 2, 3}]
Commonest[{1, 3, 2, 3}]

View file

@ -0,0 +1,75 @@
/* NetRexx */
options replace format comments java crossref symbols nobinary
run_samples()
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method mode(lvector = java.util.List) public static returns java.util.List
seen = 0
modes = ''
modeMax = 0
loop v_ = 0 to lvector.size() - 1
mv = Rexx lvector.get(v_)
seen[mv] = seen[mv] + 1
select
when seen[mv] > modeMax then do
modeMax = seen[mv]
modes = ''
nx = 1
modes[0] = nx
modes[nx] = mv
end
when seen[mv] = modeMax then do
nx = modes[0] + 1
modes[0] = nx
modes[nx] = mv
end
otherwise do
nop
end
end
end v_
modeList = ArrayList(modes[0])
loop v_ = 1 to modes[0]
val = modes[v_]
modeList.add(val)
end v_
return modeList
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method mode(rvector = Rexx[]) public static returns java.util.List
return mode(ArrayList(Arrays.asList(rvector)))
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method show_mode(lvector = java.util.List) public static returns java.util.List
modes = mode(lvector)
say 'Vector:' (Rexx lvector).space(0)', Mode(s):' (Rexx modes).space(0)
return modes
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method show_mode(rvector = Rexx[]) public static returns java.util.List
return show_mode(ArrayList(Arrays.asList(rvector)))
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method run_samples() public static
show_mode([Rexx 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) -- 10 9 8 7 6 5 4 3 2 1
show_mode([Rexx 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0.11]) -- 0
show_mode([Rexx 30, 10, 20, 30, 40, 50, -100, 4.7, -11e+2]) -- 30
show_mode([Rexx 30, 10, 20, 30, 40, 50, -100, 4.7, -11e+2, -11e+2]) -- 30 -11e2
show_mode([Rexx 1, 8, 6, 0, 1, 9, 4, 6, 1, 9, 9, 9]) -- 9
show_mode([Rexx 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) -- 1 2 3 4 5 6 7 8 9 10 11
show_mode([Rexx 8, 8, 8, 2, 2, 2]) -- 8 2
show_mode([Rexx 'cat', 'kat', 'Cat', 'emu', 'emu', 'Kat']) -- emu
show_mode([Rexx 0, 1, 2, 3, 3, 3, 4, 4, 4, 4, 1, 0]) -- 4
show_mode([Rexx 2, 7, 1, 8, 2]) -- 2
show_mode([Rexx 2, 7, 1, 8, 2, 8]) -- 8 2
show_mode([Rexx 'E', 'n', 'z', 'y', 'k', 'l', 'o', 'p', 'ä', 'd', 'i', 'e']) -- E n z y k l o p ä d i e
show_mode([Rexx 'E', 'n', 'z', 'y', 'k', 'l', 'o', 'p', 'ä', 'd', 'i', 'e', 'ä']) -- ä
show_mode([Rexx 3, 1, 4, 1, 5, 9, 7, 6]) -- 1
show_mode([Rexx 3, 1, 4, 1, 5, 9, 7, 6, 3]) -- 3, 1
show_mode([Rexx 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]) -- 6
show_mode([Rexx 1, 1, 2, 4, 4]) -- 4 1
return

View file

@ -0,0 +1,10 @@
import tables
proc modes[T](xs: openArray[T]): T =
var count = initCountTable[T]()
for x in xs:
count.inc(x)
largest(count).key
echo modes(@[1,3,6,6,6,6,7,7,12,12,17])
echo modes(@[1,1,2,4,4])

View file

@ -0,0 +1,13 @@
let mode lst =
let seen = Hashtbl.create 42 in
List.iter (fun x ->
let old = if Hashtbl.mem seen x then
Hashtbl.find seen x
else 0 in
Hashtbl.replace seen x (old + 1))
lst;
let best = Hashtbl.fold (fun _ -> max) seen 0 in
Hashtbl.fold (fun k v acc ->
if v = best then k :: acc
else acc)
seen []

View file

@ -0,0 +1,76 @@
MODULE Mode;
IMPORT
Object:Boxed,
ADT:Dictionary,
ADT:LinkedList,
Out := NPCT:Console;
TYPE
Key = Boxed.LongInt;
Val = Boxed.LongInt;
VAR
x: ARRAY 11 OF LONGINT;
y: ARRAY 5 OF LONGINT;
z: ARRAY 8 OF LONGINT;
PROCEDURE Show(ll: LinkedList.LinkedList(Key));
VAR
iter: LinkedList.Iterator(Key);
i: LONGINT;
k: Key;
BEGIN
iter := ll.GetIterator(NIL);
FOR i := 0 TO ll.Size() - 1 DO;
k := iter.Next();
Out.Int(k.value,0);Out.Ln;
END;
END Show;
PROCEDURE Mode(x: ARRAY OF LONGINT): LinkedList.LinkedList(Key);
VAR
d: Dictionary.Dictionary(Key,Val);
i: LONGINT;
k: Key; v: Val;
iter: Dictionary.IterKeys(Key,Val);
resp: LinkedList.LinkedList(Key);
max: Boxed.LongInt;
BEGIN
d := NEW(Dictionary.Dictionary(Key,Val));
FOR i := 0 TO LEN(x) - 1 DO
k := NEW(Key,x[i]);
IF d.Lookup(k,v) THEN
d.Set(k,NEW(Val,v.value + 1));
ELSE
d.Set(k,NEW(Val,1))
END
END;
max := NEW(Boxed.LongInt,0);
resp := NEW(LinkedList.LinkedList(Key));
iter := d.IterKeys();
WHILE (iter.Next(k)) DO
v := d.Get(k);
IF v.Cmp(max) > 0 THEN
resp.Clear();
resp.Append(k);max := v
ELSIF v.Cmp(max) = 0 THEN
resp.Append(k);max := v
END
END;
RETURN resp
END Mode;
BEGIN
x[0] := 1; x[1] := 3; x[2] := 6; x[3] := 6;
x[4] := 6; x[5] := 6; x[6] := 7; x[7] := 7;
x[8] := 12; x[9] := 12; x[10] := 17;
Show(Mode(x));Out.Ln;
y[0] := 1; y[1] := 2; y[2] := 4; y[3] := 4; y[4] := 1;
Show(Mode(y));Out.Ln;
z[0] := 1; z[1] := 2; z[2] := 4; z[3] := 4; z[4] := 1; z[5] := 5; z[6] := 5; z[7] := 5;
Show(Mode(z));Out.Ln;
END Mode.

View file

@ -0,0 +1,50 @@
use Collection;
class Mode {
function : Main(args : String[]) ~ Nil {
Print(Mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]));
Print(Mode([1, 2, 4, 4, 1]));
}
function : Mode(coll : Int[]) ~ IntVector {
seen := IntMap->New();
max := 0;
maxElems := IntVector->New();
each(i : coll) {
value := coll[i];
featched := seen->Find(value)->As(IntHolder);
if(featched <> Nil) {
seen->Remove(value);
seen->Insert(value, IntHolder->New(featched->Get() + 1));
}
else {
seen->Insert(value, IntHolder->New(1));
};
featched := seen->Find(value)->As(IntHolder);
if(featched->Get() > max) {
max := featched->Get();
maxElems->Empty();
maxElems->AddBack(value);
}
else if(featched->Get() = max) {
maxElems->AddBack(value);
};
};
return maxElems;
}
function : Print(out : IntVector) ~ Nil {
'['->Print();
each(i : out) {
out->Get(i)->Print();
if(i + 1 < out->Size()) {
", "->Print();
};
};
']'->PrintLine();
}
}

View file

@ -0,0 +1,24 @@
#import <Foundation/Foundation.h>
@interface NSArray (Mode)
- (NSArray *)mode;
@end
@implementation NSArray (Mode)
- (NSArray *)mode {
NSCountedSet *seen = [NSCountedSet setWithArray:self];
int max = 0;
NSMutableArray *maxElems = [NSMutableArray array];
for ( obj in seen ) {
int count = [seen countForObject:obj];
if (count > max) {
max = count;
[maxElems removeAllObjects];
[maxElems addObject:obj];
} else if (count == max) {
[maxElems addObject:obj];
}
}
return maxElems;
}
@end

View file

@ -0,0 +1,29 @@
function m = mode2(v)
sv = sort(v);
% build two vectors, vals and c, so that
% c(i) holds how many times vals(i) appears
i = 1; c = []; vals = [];
while (i <= numel(v) )
tc = sum(sv==sv(i)); % it would be faster to count
% them "by hand", since sv is sorted...
c = [c, tc];
vals = [vals, sv(i)];
i += tc;
endwhile
% stack vals and c building a 2-rows matrix x
x = cat(1,vals,c);
% sort the second row (frequencies) into t (most frequent
% first) and take the "original indices" i ...
[t, i] = sort(x(2,:), "descend");
% ... so that we can use them to sort columns according
% to frequencies
nv = x(1,i);
% at last, collect into m (the result) all the values
% having the same bigger frequency
r = t(1); i = 1;
m = [];
while ( t(i) == r )
m = [m, nv(i)];
i++;
endwhile
endfunction

View file

@ -0,0 +1,7 @@
a = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
mode2(a)
mode(a)
a = [1, 1, 2, 4, 4];
mode2(a) % returns 1 and 4
mode(a) % returns 1 only

View file

@ -0,0 +1,32 @@
-- will work with just about any collection...
call testMode .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
call testMode .list~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11)
call testMode .queue~of(30, 10, 20, 30, 40, 50, -100, 4.7, -11e2)
::routine testMode
use arg list
say "list =" list~makearray~toString("l", ", ")
say "mode =" mode(list)
say
::routine mode
use arg list
-- this is a good application for a bag
-- add all of the items to the bag
collector = .bag~new
collector~putAll(list)
-- now get a list of unique items
indexes = .set~new~~putall(collector)
count = 0 -- this is used to keep track of the maximums
-- now see how many of each element we ended up with
loop index over indexes
items = collector~allat(index)
newCount = items~items
if newCount > count then do
mode = items[1]
count = newCount
end
end
return mode

View file

@ -0,0 +1,17 @@
declare
fun {Mode Xs}
Freq = {Dictionary.new}
for X in Xs do
Freq.X := {CondSelect Freq X 0} + 1
end
MaxCount = {FoldL {Dictionary.items Freq} Max 0}
in
for Value#Count in {Dictionary.entries Freq} collect:C do
if Count == MaxCount then
{C Value}
end
end
end
in
{Show {Mode [1 2 3 3 2 1 1]}}
{Show {Mode [1 2 3 3 2 1]}}

View file

@ -0,0 +1,16 @@
mode(v)={
my(count=1,r=1,b=v[1]);
v=vecsort(v);
for(i=2,#v,
if(v[i]==v[i-1],
count++
,
if(count>r,
r=count;
b=v[i-1]
);
count=1
)
);
if(count>r,v[#v],b)
};

View file

@ -0,0 +1,10 @@
<?php
function mode($arr) {
$count = array_count_values($arr);
$best = max($count);
return array_keys($count, $best);
}
print_r(mode(array(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17)));
print_r(mode(array(1, 1, 2, 4, 4)));
?>

View file

@ -0,0 +1,20 @@
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;
declare (j, n, max, value) fixed binary;
declare i fixed;
n = hbound(x,1);
do i = 1 to n;
j = x(i);
f(j) = f(j) + 1;
end;
max = 0;
do i = 1 to hbound(f,1);
if max < f(i) then do; max = f(i); value = i; end;
end;
put list ('The mode value is ' || value || ' occurred ' ||
max || ' times.');
end av;

View file

@ -0,0 +1,12 @@
use strict;
use List::Util qw(max);
sub mode
{
my %c;
foreach my $e ( @_ ) {
$c{$e}++;
}
my $best = max(values %c);
return grep { $c{$_} == $best } keys %c;
}

View file

@ -0,0 +1,4 @@
print "$_ " foreach mode(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17);
print "\n";
print "$_ " foreach mode(1, 1, 2, 4, 4);
print "\n";

View file

@ -0,0 +1,41 @@
(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>
<span style="color: #004080;">integer</span> <span style="color: #000000;">nxt</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">maxc</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">prev</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]!=</span><span style="color: #000000;">prev</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">nxt</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">count</span><span style="color: #0000FF;">,</span><span style="color: #000000;">prev</span><span style="color: #0000FF;">}</span>
<span style="color: #000000;">nxt</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">prev</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">else</span>
<span style="color: #000000;">count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">count</span><span style="color: #0000FF;">></span><span style="color: #000000;">maxc</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">maxc</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">count</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">nxt</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">count</span><span style="color: #0000FF;">,</span><span style="color: #000000;">prev</span><span style="color: #0000FF;">}</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">nxt</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">maxc</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">2</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">mode</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">9.5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3.14159</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">mode</span><span style="color: #0000FF;">({</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"blue"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7.5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"green"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"red"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"blue"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"white"</span> <span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">mode</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">mode</span><span style="color: #0000FF;">({.</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">.</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">.</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">.</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">.</span><span style="color: #000000;">2</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">mode</span><span style="color: #0000FF;">({</span><span style="color: #008000;">"two"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"two"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">mode</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Hello there world"</span><span style="color: #0000FF;">)</span>
<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>
<!--

View file

@ -0,0 +1,7 @@
(de modes (Lst)
(let A NIL
(for X Lst
(accu 'A X 1) )
(mapcar car
(maxi cdar
(by cdr group A) ) ) ) )

View file

@ -0,0 +1,3 @@
$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}

View file

@ -0,0 +1,38 @@
Procedure mean(Array InArray(1))
Structure MyMean
Value.i
Cnt.i
EndStructure
Protected i, max, found
Protected NewList MyDatas.MyMean()
Repeat
found=#False
ForEach MyDatas()
If InArray(i)=MyDatas()\Value
MyDatas()\Cnt+1
found=#True
Break
EndIf
Next
If Not found
AddElement(MyDatas())
MyDatas()\Value=InArray(i)
MyDatas()\cnt+1
EndIf
If MyDatas()\Cnt>max
max=MyDatas()\Cnt
EndIf
i+1
Until i>ArraySize(InArray())
ForEach MyDatas()
If MyDatas()\Cnt=max
For i=1 To max
Print(Str(MyDatas()\Value)+" ")
Next
EndIf
Next
EndProcedure

View file

@ -0,0 +1,12 @@
>>> from collections import defaultdict
>>> def modes(values):
count = defaultdict(int)
for v in values:
count[v] +=1
best = max(count.values())
return [k for k,v in count.items() if v == best]
>>> modes([1,3,6,6,6,6,7,7,12,12,17])
[6]
>>> modes((1,1,2,4,4))
[1, 4]

View file

@ -0,0 +1,10 @@
>>> from collections import Counter
>>> def modes(values):
count = Counter(values)
best = max(count.values())
return [k for k,v in count.items() if v == best]
>>> modes([1,3,6,6,6,6,7,7,12,12,17])
[6]
>>> modes((1,1,2,4,4))
[1, 4]

View file

@ -0,0 +1,2 @@
def onemode(values):
return max(set(values), key=values.count)

View file

@ -0,0 +1 @@
mode:{(key x) where value x=max x} count each group @

View file

@ -0,0 +1,32 @@
[ sort
[] [] rot
dup 0 peek temp put
witheach
[ dup temp share = iff
join
else
[ dup temp replace
dip [ nested join ]
[] join ] ]
nested join
temp release ] is bunch ( [ --> [ )
[ sortwith [ size dip size < ]
[] swap
dup 0 peek size temp put
witheach
[ dup size temp share = iff
[ nested join ]
else
[ drop conclude ] ]
temp release
[] swap
witheach
[ 0 peek join ] ] is largest ( [ --> [ )
[ bunch largest ] is mode ( [ --> [ )
' [ 1 3 5 7 3 1 3 7 7 3 3 ] mode echo cr
' [ 7 13 5 13 7 2 7 10 13 ] mode echo cr
' [ 5 ] mode echo cr

View file

@ -0,0 +1,14 @@
statmode <- function(v) {
a <- sort(table(v), decreasing=TRUE)
r <- c()
for(i in 1:length(a)) {
if ( a[[1]] == a[[i]] ) {
r <- c(r, as.integer(names(a)[i]))
} else break; # since it's sorted, once we find
# a different value, we can stop
}
r
}
print(statmode(c(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17)))
print(statmode(c(1, 1, 2, 4, 4)))

View file

@ -0,0 +1,26 @@
/*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
v= 1 2 3 4 5 6 7 8 9 11 10 ; say 'vector='v; say 'mode='mode(v); say
v= 8 8 8 2 2 2 ; say 'vector='v; say 'mode='mode(v); say
v='cat kat Cat emu emu Kat' ; say 'vector='v; say 'mode='mode(v); say
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sort: procedure expose @.; parse arg # 1 h /* [↓] this is an exchange sort. */
do while h>1; h=h%2 /*In REXX, % is an integer divide.*/
do i=1 for #-h; j=i; k=h+i /* [↓] perform exchange for elements. */
do while @.k<@.j & h<j; _=@.j; @.j=@.k; @.k=_; j=j-h; k=k-h; end
end /*i*/
end /*while h>1*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
mode: procedure expose @.; parse arg x; freq=1 /*function finds the MODE of a vector*/
#=words(x) /*#: the number of elements in vector.*/
do k=1 for #; @.k=word(x,k); end /* ◄──── make an array from the vector.*/
call Sort # /*sort the elements in the array. */
?=@.1 /*assume the first element is the mode.*/
do j=1 for #; _=j-freq /*traipse through the elements in array*/
if @.j==@._ then do; freq=freq+1 /*is this element the same as previous?*/
?=@.j /*this element is the mode (···so far).*/
end
end /*j*/
return ? /*return the mode of vector to invoker.*/

View file

@ -0,0 +1,92 @@
/* Rexx */
/*-- ~~ main ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
call run_samples
return
exit
/*-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/*-- returns a comma separated string of mode values from a comma separated input vector string */
mode:
procedure
parse arg lvector
drop vector.
vector. = ''
call makeStem lvector /*-- this call creates the "vector." stem from the input string */
seen. = 0
modes. = ''
modeMax = 0
do v_ = 1 to vector.0
mv = vector.v_
seen.mv = seen.mv + 1
select
when seen.mv > modeMax then do
modeMax = seen.mv
drop modes.
modes. = ''
nx = 1
modes.0 = nx
modes.nx = mv
end
when seen.mv = modeMax then do
nx = modes.0 + 1
modes.0 = nx
modes.nx = mv
end
otherwise do
nop
end
end
end v_
lmodes = ''
do e_ = 1 to modes.0
lmodes = lmodes modes.e_
end e_
lmodes = strip(space(lmodes, 1, ','))
return lmodes
/*-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/*-- pretty-print */
show_mode:
procedure
parse arg lvector
lmodes = mode(lvector)
say 'Vector: ['space(lvector, 0)'], Mode(s): ['space(lmodes, 0)']'
return modes
/*-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/*-- load the "vector." stem from the comma separated input vector string */
makeStem:
procedure expose vector.
vector.0 = 0
parse arg lvector
do v_ = 1 while lvector \= ''
parse var lvector val ',' lvector
vector.0 = v_
vector.v_ = strip(val)
vector = strip(lvector)
end v_
return vector.0
/*-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
run_samples:
procedure
call show_mode '10, 9, 8, 7, 6, 5, 4, 3, 2, 1' -- 10 9 8 7 6 5 4 3 2 1
call show_mode '10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0.11' -- 0
call show_mode '30, 10, 20, 30, 40, 50, -100, 4.7, -11e+2' -- 30
call show_mode '30, 10, 20, 30, 40, 50, -100, 4.7, -11e+2, -11e+2' -- 30 -11e2
call show_mode '1, 8, 6, 0, 1, 9, 4, 6, 1, 9, 9, 9' -- 9
call show_mode '1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11' -- 1 2 3 4 5 6 7 8 9 10 11
call show_mode '8, 8, 8, 2, 2, 2' -- 8 2
call show_mode 'cat, kat, Cat, emu, emu, Kat' -- emu
call show_mode '0, 1, 2, 3, 3, 3, 4, 4, 4, 4, 1, 0' -- 4
call show_mode '2, 7, 1, 8, 2' -- 2
call show_mode '2, 7, 1, 8, 2, 8' -- 8 2
call show_mode 'E, n, z, y, k, l, o, p, ä, d, i, e' -- E n z y k l o p ä d i e
call show_mode 'E, n, z, y, k, l, o, p, ä, d, i, e, ä' -- ä
call show_mode '3, 1, 4, 1, 5, 9, 7, 6' -- 1
call show_mode '3, 1, 4, 1, 5, 9, 7, 6, 3' -- 3, 1
call show_mode '1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17' -- 6
call show_mode '1, 1, 2, 4, 4' -- 4 1
return

View file

@ -0,0 +1,18 @@
#lang racket
(define (mode seq)
(define frequencies (make-hash))
(for ([s seq])
(hash-update! frequencies
s
(lambda (freq) (add1 freq))
0))
(for/fold ([ms null]
[freq 0])
([(k v) (in-hash frequencies)])
(cond [(> v freq)
(values (list k) v)]
[(= v freq)
(values (cons k ms) freq)]
[else
(values ms freq)])))

View file

@ -0,0 +1,9 @@
sub mode (*@a) {
my %counts := @a.Bag;
my $max = %counts.values.max;
%counts.grep(*.value == $max).map(*.key);
}
# Testing with arrays:
say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
say mode [1, 1, 2, 4, 4];

View file

@ -0,0 +1,9 @@
sub mode (*@a) {
@a.Bag # count elements
.classify(*.value) # group elements with the same count
.max(*.key) # get group with the highest count
.value.map(*.key); # get elements in the group
}
say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
say mode [1, 1, 2, 4, 4];

View file

@ -0,0 +1,42 @@
# Project : Averages/Mode
a = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]
b = [1, 2, 4, 4, 1]
amodes = list(12)
see "mode(s) of a() = " + nl
for i1 = 1 to modes(a,amodes)
see "" + amodes[i1] + " "
next
see nl
see "mode(s) of b() = " + nl
for i1 = 1 to modes(b,amodes)
see "" + amodes [i1] + " "
next
see nl
func modes(a,amodes)
max = 0
n = len(a)
if n = 0
amodes[1] = a[1]
return 1
ok
c = list(n)
for i = 1 to n
for j = i+1 to n
if a[i] = a[j]
c[i] = c[i] + 1
ok
next
if c[i] > max
max = c[i]
ok
next
j = 0
for i = 1 to n
if c[i] = max
j = j + 1
amodes[j] = a[i]
ok
next
return j

Some files were not shown because too many files have changed in this diff Show more