This commit is contained in:
Ingy döt Net 2013-04-10 15:42:53 -07:00
parent 051504d65b
commit 0457928c3e
295 changed files with 3588 additions and 3 deletions

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,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,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,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 = *(double*)a - *(double*)b;
return x < 0 ? -1 : x > 0;
}
int vc_cmp(const void *a, const void *b)
{
return ((vcount*)b)->c - ((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,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,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,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,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,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,30 @@
function mode (numlist)
if type(numlist) ~= 'table' then return numlist end
local sets = {}
local mode
local modeValue = 0
table.foreach(numlist,function(i,v) if sets[v] then sets[v] = sets[v] + 1 else sets[v] = 1 end end)
for i,v in next,sets do
if v > modeValue then
modeValue = v
mode = i
else
if v == modeValue then
if type(mode) == 'table' then
table.insert(mode,i)
else
mode = {mode,i}
end
end
end
end
return mode
end
result = mode({1,3,6,6,6,6,7,7,12,12,17})
print(result)
result = mode({1, 1, 2, 4, 4})
if type(result) == 'table' then
for i,v in next,result do io.write(v..' ') end
print ()
end

View file

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

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,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,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,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,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,34 @@
/*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 10 11' ; 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 done.*/
/*──────────────────────────────────MAKEARRAY subroutine────────────────*/
makeArray: procedure expose @.; parse arg v; @.0=words(v) /*make array*/
do k=1 for @.0; @.k=word(v,k); end /*k*/
return
/*──────────────────────────────────ESORT subroutine────────────────────*/
esort: procedure expose @.; h=@.0 /*exchange sort.*/
do while h>1; h=h%2
do i=1 for @.0-h; j=i; k=h+i
do while @.k<@.j;t=@.j;@.j=@.k;@.k=t;if h>=j then leave;j=j-h;k=k-h;end
end /*i*/
end /*while h>1*/
return
/*──────────────────────────────────MODE subroutine─────────────────────*/
mode: procedure expose @.; parse arg x /*finds the MODE of a vector. */
call makeArray x /*make an array out of the vector*/
call esort @.0 /*sort the array elements. */
?=@.1 /*assume 1st element is the mode.*/
freq=1 /*the frequency of the occurance.*/
do j=1 for @.0; _=j-freq
if @.j==@._ then do
freq=freq+1 /*bump the frequency count. */
?=@.j /*this is the one. */
end
end /*j*/
return ?

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,27 @@
def mode(ary)
seen = Hash.new(0)
ary.each {|value| seen[value] += 1}
max = seen.values.max
seen.find_all {|key,value| value == max}.map {|key,value| key}
end
def mode_one_pass(ary)
seen = Hash.new(0)
max = 0
max_elems = []
ary.each do |value|
seen[value] += 1
if seen[value] > max
max = seen[value]
max_elems = [value]
elsif seen[value] == max
max_elems << value
end
end
max_elems
end
p mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]) # => [6]
p mode([1, 1, 2, 4, 4]) # => [1, 4]
p mode_one_pass([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]) # => [6]
p mode_one_pass([1, 1, 2, 4, 4]) # => [1, 4]

View file

@ -0,0 +1,3 @@
def one_mode(ary)
ary.max_by { |x| ary.count(x) }
end

View file

@ -0,0 +1,10 @@
import scala.collection.breakOut
import scala.collection.generic.CanBuildFrom
def mode
[T, CC[X] <: Seq[X]](coll: CC[T])
(implicit o: T => Ordered[T], cbf: CanBuildFrom[Nothing, T, CC[T]])
: CC[T] = {
val grouped = coll.groupBy(x => x).mapValues(_.size).toSeq
val max = grouped.map(_._2).max
grouped.filter(_._2 == max).map(_._1)(breakOut)
}

View file

@ -0,0 +1,10 @@
(define (mode collection)
(define (helper collection counts)
(if (null? collection)
counts
(helper (remove (car collection) collection)
(cons (cons (car collection)
(appearances (car collection) collection)) counts))))
(map car
(filter (lambda (x) (= (cdr x) (apply max (map cdr (helper collection '())))))
(helper collection '())))

View file

@ -0,0 +1,11 @@
OrderedCollection extend [
mode [ |s|
s := self asBag sortedByCount.
^ (s select: [ :k | ((s at: 1) key) = (k key) ]) collect: [:k| k value]
]
].
#( 1 3 6 6 6 6 7 7 12 12 17 ) asOrderedCollection
mode displayNl.
#( 1 1 2 4 4) asOrderedCollection
mode displayNl.

View file

@ -0,0 +1,18 @@
# Can find the modal value of any vector of values
proc mode {n args} {
foreach n [list $n {*}$args] {
dict incr counter $n
}
set counts [lsort -stride 2 -index 1 -decreasing $counter]
set best {}
foreach {n count} $counts {
if {[lindex $counts 1] == $count} {
lappend best $n
} else break
}
return $best
}
# Testing
puts [mode 1 3 6 6 6 6 7 7 12 12 17]; # --> 6
puts [mode 1 1 2 4 4]; # --> 1 4