[Issue 9842] std.algorithm.hashGroup / hashGroupBy
via Digitalmars-d-bugs
digitalmars-d-bugs at puremagic.com
Wed Dec 17 01:54:27 PST 2014
https://issues.dlang.org/show_bug.cgi?id=9842
--- Comment #3 from bearophile_hugs at eml.cc ---
Another example usage. Here the "properDivs" function returns the proper
divisors of the given number n. The function "classify" returns one of the
three classes (Deficient number, Perfect number, Abundant number). Then a
hashGroup is handy to create an associative array to count how many numbers
there are of each class in the [1,10000] interval:
void main() {
import std.stdio, std.algorithm, std.range;
static immutable properDivs = (in uint n) pure nothrow @safe =>
iota(1, (n + 1) / 2 + 1).filter!(x => n % x == 0 && n != x);
enum Class { deficient, perfect, abundant }
static Class classify(in uint n) pure nothrow @safe {
immutable p = properDivs(n).sum;
with (Class)
return (p < n) ? deficient : ((p == n) ? perfect : abundant);
}
iota(1, 10000).map!classify.hashGroup.writeln;
}
--
More information about the Digitalmars-d-bugs
mailing list