2016 Update

This commit is contained in:
Tina Müller 2016-12-05 22:15:40 +01:00
parent 948b86eafa
commit dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions

View file

@ -1,5 +1,13 @@
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.
{{task heading}}
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.
See also: [[Averages/Arithmetic mean|Mean]], [[Averages/Median|Median]]
{{task heading|See also}}
{{Related tasks/Statistical measures}}
<hr>

View file

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

View file

@ -1,30 +1,27 @@
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
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
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
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,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,5 @@
sub mode (*@a) {
my %counts := @a.Bag;
my $max = %counts.values.max;
return |%counts.grep(*.value == $max).map(*.key);
}

View file

@ -0,0 +1,2 @@
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,8 @@
sub mode (*@a) {=
return |(@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
);
}

View file

@ -1,6 +0,0 @@
sub mode (@a) {
my %counts;
++%counts{$_} for @a;
my $max = [max] values %counts;
return map { .key }, grep { .value == $max }, %counts.pairs;
}

View file

@ -1,29 +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 done.*/
/*──────────────────────────────────ESORT subroutine────────────────────*/
Esort: procedure expose @.; h=@.0 /* [↓] exchange sort. */
do while h>1; h=h%2 /*% is integer divide.*/
do i=1 for @.0-h; j=i; k=h+i /* [↓] perform exchange*/
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 subroutine─────────────────────*/
mode: procedure expose @.; parse arg x /*finds the MODE of a vector. */
@.0=words(x) /* [↓] make an array from vector.*/
do k=1 for @.0; @.k=word(x,k); end /*k*/
call Esort @.0 /*sort the elements in the array.*/
?=@.1 /*assume 1st element is the mode.*/
freq=1 /*the frequency of the occurrence*/
do j=1 for @.0; _=j-freq /*traipse through the elements. */
if @.j==@._ then do /*this element same as previous? */
freq=freq+1 /*bump the frequency counter. */
?=@.j /*this element is the mode,so far*/
end
end /*j*/
return ? /*return the node to the invoker.*/
/*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

@ -1,17 +1,17 @@
/* Rexx */
-- ~~ main ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*-- ~~ main ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
call run_samples
return
exit
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- returns a comma separated string of mode values from a comma separated input vector string
/*-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/*-- 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
call makeStem lvector /*-- this call creates the "vector." stem from the input string */
seen. = 0
modes. = ''
modeMax = 0
@ -46,8 +46,8 @@ mode:
return lmodes
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- pretty-print
/*-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/*-- pretty-print */
show_mode:
procedure
parse arg lvector
@ -55,8 +55,8 @@ show_mode:
say 'Vector: ['space(lvector, 0)'], Mode(s): ['space(lmodes, 0)']'
return modes
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- load the "vector." stem from the comma separated input vector string
/*-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/*-- load the "vector." stem from the comma separated input vector string */
makeStem:
procedure expose vector.
vector.0 = 0
@ -69,7 +69,7 @@ makeStem:
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

View file

@ -0,0 +1,31 @@
use std::collections::HashMap;
fn main() {
let mode_vec1 = mode(vec![ 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]);
let mode_vec2 = mode(vec![ 1, 1, 2, 4, 4]);
println!("Mode of vec1 is: {:?}", mode_vec1);
println!("Mode of vec2 is: {:?}", mode_vec2);
assert!( mode_vec1 == [6], "Error in mode calculation");
assert!( (mode_vec2 == [1, 4]) || (mode_vec2 == [4,1]), "Error in mode calculation" );
}
fn mode(vs: Vec<i32>) -> Vec<i32> {
let mut vec_mode = Vec::new();
let mut seen_map = HashMap::new();
let mut max_val = 0;
for i in vs{
let ctr = seen_map.entry(i).or_insert(0);
*ctr += 1;
if *ctr > max_val{
max_val = *ctr;
}
}
for (key, val) in seen_map {
if val == max_val{
vec_mode.push(key);
}
}
vec_mode
}

View file

@ -0,0 +1,39 @@
private variable mx, mxkey, modedat;
define find_max(key) {
if (modedat[key] > mx) {
mx = modedat[key];
mxkey = {key};
}
else if (modedat[key] == mx) {
list_append(mxkey, key);
}
}
define find_mode(indat)
{
% reset [file/module-scope] globals:
mx = 0, mxkey = {}, modedat = Assoc_Type[Int_Type, 0];
foreach $1 (indat)
modedat[string($1)]++;
array_map(Void_Type, &find_max, assoc_get_keys(modedat));
if (length(mxkey) > 1) {
$2 = 0;
() = printf("{");
foreach $1 (mxkey) {
() = printf("%s%s", $2 ? ", " : "", $1);
$2 = 1;
}
() = printf("} each have ");
}
else
() = printf("%s has ", mxkey[0], mx);
() = printf("the most entries (%d).\n", mx);
}
find_mode({"Hungadunga", "Hungadunga", "Hungadunga", "Hungadunga", "McCormick"});
find_mode({"foo", "2.3", "bar", "foo", "foobar", "quality", 2.3, "strnen"});

View file

@ -28,14 +28,14 @@ const proc: createModeFunction (in type: elemType) is func
const func string: str (in array elemType: data) is func
result
var string: result is "";
var string: stri is "";
local
var elemType: anElement is elemType.value;
begin
for anElement range data do
result &:= " " & str(anElement);
stri &:= " " & str(anElement);
end for;
result := result[2 ..];
stri := stri[2 ..];
end func;
enable_output(array elemType);