On 28-04-2011 13:02, bearophile wrote:
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
The fact that 'i' and 'j' are deduced to type 'uint' in the second
version. That's the kind of bug that would keep me up at night.
Cheers,
Pedro Rodrigues