Averages/Mode: Difference between revisions

m
(→‎{{header|Vlang}}: Rename "Vlang" in "V (Vlang)")
imported>Arakov
 
(12 intermediate revisions by 7 users not shown)
Line 315:
<pre>Input: 1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6
Result: 2, 3</pre>
 
=={{header|ALGOL 68}}==
{{libheader|ALGOL 68-rows}}
This sample defines an operator to return the mode(s) of an integer array. Additional operators cound be defined for other array types.
<br>Note the source of rows.incl.a68 (containing the QUICKSORT and SHOW operators) is available on a page in Rosetta Code, see the above link.
<syntaxhighlight lang="algol68">
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
</syntaxhighlight>
{{out}}
<pre>
6
1 4
3
7 13
5
9
</pre>
 
=={{header|APL}}==
Line 860 ⟶ 939:
maxCount := maxCount.max(newCount)</syntaxhighlight>
In for loops, each key and value from the collection are [[Pattern Matching|pattern matched]] against the specified <code><var>key pattern</var> => <var>value pattern</var></code>. In "<code>for v => ==maxCount in counts</code>", the <code>==</code> is a pattern-match operator which fails unless the value examined is equal to the specified value; so this selects only the input values (keys in <code>counts</code>) whose counts are equal to the maximum count.
 
=={{header|EasyLang}}==
<syntaxhighlight>
proc modes . in[] r[] .
r[] = [ ]
for v in in[]
for i to len vals[]
if v = vals[i]
cnt[i] += 1
max = higher cnt[i] max
break 1
.
.
vals[] &= v
cnt[] &= 0
.
for i to len cnt[]
if cnt[i] = max
r[] &= vals[i]
.
.
.
in[] = [ 1 3 6 6 6 6 7 7 12 12 17 ]
modes in[] mods[]
print mods[]
in[] = [ 1 1 2 4 4 ]
modes in[] mods[]
print mods[]
</syntaxhighlight>
 
=={{header|EchoLisp}}==
Line 882 ⟶ 990:
 
=={{header|Elena}}==
ELENA 56.0x:
<syntaxhighlight lang="elena">import system'routines;
import system'collections;
Line 892 ⟶ 1,000:
{
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()
}
Line 910 ⟶ 1,018:
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()
}</syntaxhighlight>
{{out}}
Line 1,322 ⟶ 1,430:
As of the 2022-07-31 release of Frink, the function can be rewritten as:
<syntaxhighlight lang="frink">modes[vals] := mostCommon[vals]@0</syntaxhighlight>
 
=={{header|FutureBasic}}==
FB has a native function for an array of mode averages.
<syntaxhighlight lang="futurebasic">
local fn ModeAverage( arguments as CFArrayRef ) as CFStringRef
ExpressionRef expRef = fn ExpressionForFunction( @"mode:", @[fn ExpressionForConstantValue( arguments )] )
CFArrayRef modeArray = fn ExpressionValueWithObject( expRef, NULL, NULL )
CFNumberRef number
CFMutableStringRef modeStr = fn MutableStringNew
for number in modeArray
MutableStringAppendFormat( modeStr, @"value = %@\n", number )
next
end fn = modeStr
 
print fn ModeAverage( @[@1, @3, @6, @6, @6, @6, @7, @7, @12, @12, @12, @12, @17] )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
value = 6
value = 12
</pre>
 
 
=={{header|GAP}}==
Line 1,641 ⟶ 1,773:
1 4
</pre>
 
=={{header|Jakt}}==
An empty set is returned if the iterable is empty.
 
<syntaxhighlight lang="jakt">
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()))
}
</syntaxhighlight>
 
=={{header|Java}}==
Line 3,010 ⟶ 3,193:
mode(s) of b() =
1 4
</pre>
 
=={{header|RPL}}==
∑VAL and ∑CNT are global lists used to store rep. values and counters.
Using the stack to handle potentially big amounts of data would slow down execution.
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
'''IF ∑VAL''' OVER POS
'''THEN '∑CNT'''' LAST ∑'''CNT''' OVER GET 1 + PUT DROP
'''ELSE ∑VAL''' SWAP + ''''∑VAL'''' STO '''∑CNT''' 1 + ''''∑CNT'''' STO '''END'''
≫ ''''∑ADD'''' STO
≪ → data
≪ { } DUP ''''∑VAL'''' STO ''''∑CNT'''' STO
1 data SIZE '''FOR''' j
data j GET '''∑ADD NEXT'''
'''∑CNT''' LIST→ { } + →ARRY RNRM { }
1 '''∑VAL''' SIZE '''FOR''' j
'''IF''' OVER ''''∑CNT'''' j GET ==
'''THEN '∑VAL'''' j GET
'''IF''' DUP2 POS NOT '''THEN''' + '''END'''
'''END NEXT'''
≫ ''''MODE'''' STO
|
'''∑ADD''' ''( n -- )'' // update ∑VAL and ∑CNT
if n already in ∑VAL
then increment corresponding position in ∑CNT
else create new in ∑VAL / ∑CNT entries
'''MODE''' ''( { data } -- { modal value(s) } )''
initialize ∑VAL and ∑CNT
for all input values
count occurrences
get max value in ∑CNT
for all distinct values
if count = max
then get value
and add it to output list if not already in
|}
 
{ 1 3 6 6 6 6 7 7 12 12 17 } '''MODE'''
{ 1 1 2 4 4 } '''MODE'''
{{out}}
<pre>
2: { 6 }
1: { 1 4 }
</pre>
 
Line 3,490 ⟶ 3,727:
 
=={{header|Wren}}==
<syntaxhighlight lang="ecmascriptwren">class Arithmetic {
static mode(arr) {
var map = {}
Line 3,528 ⟶ 3,765:
(push value modes))))
modes))</syntaxhighlight>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">proc Mode(Size, Array); \Show the mode(s) of Array
int Size, Array;
int List, Count I, J, K, Max;
[List:= Reserve(Size*4); \4 bytes per integer
Count:= Reserve(Size*4);
K:= 0;
for I:= 0 to Size-1 do
[for J:= 0 to K-1 do
if List(J) = Array(I) then \item is in List
[Count(J):= Count(J)+1; \ so increment its count
J:= Size;
];
if J = K then \not already in List
[List(K):= Array(I);
Count(K):= 1;
K:= K+1;
];
];
Max:= 0; \find maximum count
for J:= 0 to K-1 do
if Count(J) > Max then
Max:= Count(J);
for J:= 0 to K-1 do \show Array item(s) with Max Count
if Count(J) = Max then
[IntOut(0, List(J)); ChOut(0, ^ )];
];
 
Mode(9, [1,2,3,4,5,5,5123,2,3])
</syntaxhighlight>
{{out}}
<pre>
2 3 5 </pre>
 
=={{header|Yabasic}}==
Anonymous user