forked from benhoyt/countwords
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptimized.d
36 lines (32 loc) · 772 Bytes
/
optimized.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import std.stdio;
import std.string;
import std.algorithm.iteration : splitter;
import std.algorithm.sorting : schwartzSort;
char mytolower(char c) {
mixin("char lc = 'a' - 'A';");
if (c < 'A' || c > 'Z') {
return c;
}
return cast(char)(c + lc);
}
void main() {
int[string] freq;
char[] buf;
while (stdin.readln(buf) && !stdin.eof()) {
foreach (word; splitter(buf)) {
for (ptrdiff_t idx = 0; idx < word.length; idx++) {
word[idx] = mytolower(word[idx]);
}
if (auto ptr = (word in freq)) {
++*ptr;
}
else {
freq[cast(immutable char[])word.dup] = 1;
}
}
}
auto ordered = schwartzSort!(k => freq[k], "a > b")(freq.keys);
foreach (k; ordered) {
writeln(k," ", freq[k]);
}
}