Matrix creation quiz

bearophile bearophileHUGS at lycos.com
Thu Apr 28 05:02:40 PDT 2011


A little quiz. This is related to a recent post of mine in the main D newsgroup, but please don't take a look at that post yet. This is the original function:


double[][] matgen(int n) {
    double[][] a;
    double tmp = 1.0 / n / n;
    a.length = n;
    for (int i = 0; i < n; ++i) a[i].length = n;
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < n; ++j)
            a[i][j] = tmp * (i - j) * (i + j);
    return a;
}


Second "improved" version:

double[][] matgen(int n) {
    double tmp = 1.0 / n / n;
    auto a = new double[][](n, n);
    foreach (i, row; a)
        foreach (j, ref x; row)
            x = tmp * (i - j) * (i + j);
    return a;
}


But the second nicer version has a bug, do you see it? :-)

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list