Ranges and random numbers -- again

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Tue Jun 18 08:26:21 PDT 2013


On 06/18/2013 03:38 PM, H. S. Teoh wrote:
> Well, .save *is* used in a few places; the few that I know of include
> cartesianProduct (at least one of the ranges need to be iterated over
> repeatedly in order to compute the product), and find(), I believe,
> where the needle needs to be at least a forward range so that multiple
> candidate subranges can be checked repeatedly. And joiner forwards .save
> to its wrapper range, though it doesn't actually call it as part of its
> operation. There may be a few other places where .save is used.

Try:

    auto gen = new MtClass19937(1001);
    auto t1 = gen.take(2);
    auto t2 = gen.take(2);
    writeln(cartesianProduct(t1, t2));

    auto t3 = gen.take(2);
    auto t4 = gen.take(2);
    writeln(cartesianProduct(t3, t4));

The results are interesting.  t1 and t2 are evaluated to be equal to one
another, but it looks like the original source range is consumed, as t3 and t4
are equal to one another but different from t1 and t2.

Now try:

    auto gen = new MtClass19937(1001);
    auto t1 = gen.take(2);
    auto t2 = gen.take(2);
    writeln(cartesianProduct(t1, iota(2)));
    writeln(cartesianProduct(t1, iota(2)));
    writeln(cartesianProduct(t1, iota(2)));
    writeln(cartesianProduct(t1, iota(2)));

... identical results all round.  The first argument is not consumed,
cartesianProduct must iterate only over a saved copy.

NOW try:

    auto gen = new MtClass19937(1001);
    auto t1 = gen.take(2);
    auto t2 = gen.take(2);
    writeln(cartesianProduct(iota(2), t1));
    writeln(cartesianProduct(iota(2), t1));
    writeln(cartesianProduct(iota(2), t2));
    writeln(cartesianProduct(iota(2), t2));

... and the results keep changing.  The first argument to cartesianProduct is
not consumed, the second is.

I feel very uncomfortable about the idea of cases like this where the
consumption of the source of randomness is so unpredictable.


More information about the Digitalmars-d mailing list