Replacing nested loops foreach using map/each/etc

Dennis Ritchie via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 25 08:46:52 PDT 2015


On Monday, 25 May 2015 at 15:06:45 UTC, Alex Parrill wrote:
> Hint: Use `cartesianProduct` [1] with three iota ranges to 
> replace the foreachs, and `filter` to replace the if
>
> [1] 
> http://dlang.org/phobos/std_algorithm_setops.html#.cartesianProduct

Thank you. Is it possible to replace the loop `foreach` function 
`each` or `chunkBy` with the auxiliary functions?

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

void main() {

     const x = 12, y = 65, z = 50, s = 1435;

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

     foreach (idx; cartesianProduct(a, a, a).filter!(i => i[0] * 
(y + 3 * z) + i[1] * (y + 2 * z) + i[2] * (y + z) == s)) {
         writeln(idx[0] + idx[1] + idx[2]);
         writeln(idx[0] * 3 + idx[1] * 2 + idx[2]);
         writeln(idx[0] * 3 + idx[1] * 2 + idx[2]);
         writeln(idx[0], idx[1], idx[2]);
     }
}
-----
http://rextester.com/HZP96719


More information about the Digitalmars-d-learn mailing list