Jump to content

Averages/Mode: Difference between revisions

Line 2,427:
I'm accepting strings and numbers, although I'm converting numbers to strings,
as S-Lang Assoc_Type only accepts strings as keys.
<lang S-lang>private variable modedatmx, = Assoc_Type[Int_Typemxkey, 0]modedat;
variable indat = {"foo", "2.3", "bar", "foo", "foobar", "quality", 2.3, "strnen"};
 
foreach $1 (indat)
modedat[string($1)]++;
 
variable mx = 0, mxkey = {};
define find_max(key) {
if (modedat[key] > mx) {
Line 2,444 ⟶ 2,439:
}
 
define find_mode(indat)
array_map(Void_Type, &find_max, assoc_get_keys(modedat));
{
if (length(mxkey) > 1) {
% reset [file/module-scope] globals:
$2 = 0;
mx = 0, mxkey = {}, modedat = Assoc_Type[Int_Type, 0];
foreach $1 (mxkey) {
 
() = printf("%s%s", $2 ? ", " : "", $1);
foreach $21 = 1;(indat)
modedat[string($1)]++;
 
array_map(Void_Type, &find_max, assoc_get_keys(modedat));
 
if (length(mxkey) > 1) {
$2 = 0;
() = printf(" each have {");
foreach $1 (indatmxkey) {
() = printf("%s%s", $2 ? ", " : "", $1);
$2 = 1;
}
() = printf("%s} haseach ",have mxkey[0], mx");
}
else
() = printf(" each have ");
() = printf("%s has ", mxkey[0], mx);
() = printf("the most entries at (%d).\n", mx);</lang>
}
else
() = printf("%s has ", mxkey[0], mx);
() = printf("the most entries at %d\n", mx);</lang>
 
find_mode({"Hungadunga", "Hungadunga", "Hungadunga", "Hungadunga", "McCormick"});
 
variable indat = find_mode({"foo", "2.3", "bar", "foo", "foobar", "quality", 2.3, "strnen"});</lang>
{{out}}
<pre>foo,Hungadunga 2.3 each havehas the most entries at 2</pre>(4).
{foo, 2.3} each have the most entries (2).</pre>
 
=={{header|Scala}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.