Replacing nested loops foreach using map/each/etc

Dennis Ritchie via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 25 12:34:39 PDT 2015


On Monday, 25 May 2015 at 19:16:04 UTC, anonymous wrote:
> On Monday, 25 May 2015 at 17:52:09 UTC, Dennis Ritchie wrote:
>> But why is the solution breaks down when `s = 10000` ? :)
>>
>> import std.stdio, std.algorithm, std.range;
>>
>> int c;
>> const x = 12, y = 65, z = 50, s = 100000;
>
> Which is it, now? 4 or 5 zeros?

No difference!

>> void solve(Range)(Range r) {
>> 	cartesianProduct(r, r, r).filter!(i => i[0] * (y + 3 * z) + 
>> i[1] * (y + 2 * z) + i[2] * (y + z) == s).each!dout;
>> }
>>
>> void main() {
>>
>>    auto a = iota(0, x + 1).array;
>>
>>    solve(a);
>>
>>    writefln(`%s total`, c);
>> }
>>
>> void dout(Tuple)(Tuple idx) {
>>    ++c;
>> }
>> -----
>> http://rextester.com/XGDL26042
>
> What do you mean it "breaks down"? Your original code doesn't 
> print anything for s = 10_000 or s = 100_000, either.

Excuse me, this is my blemish! I forgot that the constant `x` 
depends on `s`. Everything works correctly:

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

void solve(Range)(Range r) {
     cartesianProduct(r, r, r).filter!(i => i[0] * (y + 3 * z) + 
i[1] * (y + 2 * z) + i[2] * (y + z) == s).each!dout;
}

const y = 65, z = 50, s = 100000;
const x = s / (y + z);

void main() {

     auto a = iota(0, x + 1);

     solve(a);
}

auto dout(Tuple)(Tuple idx) {
     writefln(`%s apples`, idx[0] + idx[1] + idx[2]);
     writefln(`%s gingerbread`, idx[0] * 3 + idx[1] * 2 + idx[2]);
     writefln(`%s pharynx tea`, idx[0] * 3 + idx[1] * 2 + idx[2]);
     writefln("Sour: %s; semi-acid: %s; sweet: %s.\n", idx[0], 
idx[1], idx[2]);
}
-----
http://rextester.com/MMCI9993


More information about the Digitalmars-d-learn mailing list