Replacing nested loops foreach using map/each/etc
Alex Parrill via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon May 25 08:06:44 PDT 2015
On Monday, 25 May 2015 at 14:25:52 UTC, Dennis Ritchie wrote:
> Hi,
> Is it possible to write such a construction that could push
> immediately to a conditional statement without using nested
> loops? Ie organize search directly in the iterator if provided
> by a map / each / iota and other support functions.
> Ie I want to write this code shorter :)
>
> import std.stdio;
>
> void main() {
>
> const x = 12, y = 65, z = 50, s = 1435;
>
> foreach (i; 0 .. x + 1)
> foreach (j; 0 .. x + 1)
> foreach (k; 0 .. x + 1)
> if (i * (y + 3 * z) + j * (y + 2 * z) + k * (y
> + z) == s) {
> writeln(i + j + k);
> writeln(i * 3 + j * 2 + k);
> writeln(i * 3 + j * 2 + k);
> writeln(i, j, k);
> }
> }
> -----
> http://rextester.com/SJTU87854
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
More information about the Digitalmars-d-learn
mailing list