multiSort for sorting AA by value
Chris via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Apr 21 04:10:24 PDT 2015
The following works great. It sorts an AA by value:
1. by frequency of word
2. by alphabetic order (if two or more words have the same value)
import std.stdio : writefln;
import std.algorithm.sorting : multiSort;
void main() {
size_t[string] wcount = [
"hamster":5,
"zorro":80,
"troll":90,
"algorithm":80,
"beer":80
];
struct Word { string word; size_t count; }
Word[] sorter;
foreach (ref k, ref v; wcount)
sorter ~= Word(k, v);
assert(wcount.length == sorter.length);
sorter.multiSort!("a.count > b.count", "a.word < b.word");
assert(sorter[2].word == "beer");
foreach (ref it; sorter)
writefln("%s : %d", it.word, it.count);
}
I'm happy with it, but maybe there is a more concise
implementation?
More information about the Digitalmars-d-learn
mailing list