http://d.puremagic.com/issues/show_bug.cgi?id=5466



--- Comment #3 from bearophile_h...@eml.cc 2012-02-29 14:18:53 PST ---
This example shows an use case of byItem. Given a string, the task here is to
show the char frequencies, putting higher frequencies on top, and sorting
alphabetically the chars that share the same frequency.

A Python 2.6 program that solves the problem:


from collections import defaultdict
text = "the d programming language is an object oriented " + \
       "imperative multi paradigm system programming " + \
       "language created by walter bright of digital mars"
frequences = defaultdict(int)
for c in text:
    frequences[c] += 1
pairs = sorted(frequences.iteritems(), key=lambda (c,f): (-f,c))
for (c, f) in pairs:
    print f, c



The output of the Python program:

20  
14 a
12 e
11 g
11 i
11 r
10 t
9 m
6 n
5 d
5 l
5 o
4 p
4 s
3 b
3 u
2 c
2 h
2 y
1 f
1 j
1 v
1 w



Three different solutions in D (probably there are other solutions, maybe even
better ones) using Phobos:


import std.stdio, std.typecons, std.algorithm, std.array;

void main() {
    auto text = "the d programming language is an object oriented " ~
                "imperative multi paradigm system programming " ~
                "language created by walter bright of digital mars";

    int[char] frequences;
    foreach (char c; text)
        frequences[c]++;

    Tuple!(int,char)[] pairs1 = array(map!(c => tuple(frequences[c],
c))(frequences.byKey));
    schwartzSort!(p => tuple(-p[0], p[1]))(pairs1);
    foreach (pair; pairs1)
        writeln(pair[0], " ", pair[1]);
    writeln();

    import std.conv;
    dchar[] keys = to!(dchar[])(frequences.keys);
    schwartzSort!(c => tuple(-frequences[cast(char)c], c))(keys);
    foreach (dchar c; keys)
        writeln(frequences[cast(char)c], " ", c);
    writeln();

    Tuple!(int,char)[] pairs1b = array(map!(c => tuple(-frequences[c],
c))(frequences.byKey));
    sort(pairs1b);
    foreach (pair; pairs1b)
        writeln(-pair[0], " ", pair[1]);
    writeln();
}



A version using AA.byPair (or AA.pairs) (I have not used 'auto' for type
clarity):

Tuple!(char,int)[] pairs2 = array(frequences.byPair);
schwartzSort!(c_f => tuple(-c_f[1], c_f[0]))(pairs2);
foreach (c_f; pairs2)
    writeln(c_f[1], " ", c_f[0]);


With the eager AA.pairs and tuple unpacking syntax too:

Tuple!(char,int)[] pairs3 = frequences.pairs;
schwartzSort!(tuple(c,f) => tuple(-f, c))(pairs3);
foreach ((c, f); pairs3)
    writeln(f, " ", c);


With AA.byPair, tuple unpacking syntax and schwartzSorted, this is approaching
the Python version:

Tuple!(char,int)[] pairs4 = schwartzSorted!(tuple(c,f) => tuple(-f,
c))(frequences.byPair);
foreach ((c, f); pairs4)
    writeln(f, " ", c);

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------

Reply via email to