multiSort for sorting AA by value

bearophile via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Apr 21 04:46:23 PDT 2015


Chris:

> I'm happy with it, but maybe there is a more concise 
> implementation?

This is a bit shorter and a bit better (writefln is not yet able 
to format tuples nicely):


void main() {
     import std.stdio: writeln;
     import std.algorithm.sorting: multiSort;
     import std.array: array;

     const size_t[string] wCount = [
         "hamster": 5,
         "zorro": 80,
         "troll": 90,
         "algorithm": 80,
         "beer": 80
     ];

     auto pairs = wCount.byKeyValue.array;
     assert(wCount.length == pairs.length);
     pairs.multiSort!(q{a.value > b.value}, q{a.key < b.key});
     assert(pairs[2].key == "beer");
     foreach (const ref it; pairs)
         writeln(it.key, ": ", it.value);
}


Bye,
bearophile


More information about the Digitalmars-d-learn mailing list