[Issue 4725] std.algorithm.sum()

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sat May 4 13:27:39 PDT 2013


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



--- Comment #20 from bearophile_hugs at eml.cc 2013-05-04 13:27:36 PDT ---
An use case. Given some permutations of the chars "ABCD" this program finds the
missing one:


import std.stdio, std.string, std.algorithm, std.conv, std.range;

void main() {
    const perms = "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC
                   BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD
                   BADC BDAC CBDA DBCA DCAB".split;

    immutable rowSum = perms[0].reduce!q{a + b};

    foreach (immutable i; 0 .. perms[0].length) {
        immutable sumColumns = reduce!q{a + b}(0, perms.transversal(i));
        write(cast(char)(rowSum - sumColumns % rowSum));
    }
    writeln;
}


Output: DBAC


Using a sum() function:


import std.stdio, std.string, std.algorithm, std.conv, std.range;

void main() {
    const perms = "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC
                   BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD
                   BADC BDAC CBDA DBCA DCAB".split;

    immutable rowSum = perms[0].sum(0);

    foreach (immutable i; 0 .. perms[0].length) {
        immutable sumColumns = perms.transversal(i).sum(0);
        write(cast(char)(rowSum - sumColumns % rowSum));
    }
    writeln;
}


As in the Python sum() I have added a seed value, in this case the 0 int.

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


More information about the Digitalmars-d-bugs mailing list