Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex updating rule in 'for' loop

I'm trying to write the following 'while' loop:

int x = N-1, y = 0;

while ( y < M ) {

    /* Some work */

    if ( x > 0 )
        x--;
    else 
        y++;

}

as a 'for' loop. This was my failed attempt:

for ( int x = N-1, y = 0 ; y < M ; ((x>0)?x--:y++) ) {
    /* Some work */
}

This fails to compile since, as the compiler says, the update rule is not a statement.

Do you see any way to naturally write the 'while' loop above as a 'for' loop?

like image 862
naitoon Avatar asked Dec 19 '12 14:12

naitoon


3 Answers

You can always leave the update rule empty

for ( int x = N-1, y = 0 ; y < M ; ) {

 if ( x > 0 )
        x--;
    else 
        y++;

}
like image 127
Damian Leszczyński - Vash Avatar answered Sep 20 '22 19:09

Damian Leszczyński - Vash


To combine the conditions.

 for(int x = N-1, y = 0; y < M ; y += (x > 0)?0:1, x += (x > 0)?-1:0)

I suspect this should really be two loops calling a common method.

 for(int x = N - 1; x >= 0; x--)
     someMethod(x, 0);
 for(int y = 0; y < M; y++)
     someMethod(0, y);
like image 42
Peter Lawrey Avatar answered Sep 20 '22 19:09

Peter Lawrey


Does

/* Some work */

include the variables x and y? If not, there is an easier way to write the logic of the loop. Currently, your loops counts from N-1 to zero (x) and then from zero to M-1 (y). The entire loop runs (M+N)-1 times.

By combining the initial conditions, you can write:

for (int x = 1; x < M+N; x++) {
    /* Some work */
}

and do away with the y variable altogether.

If you need to keep the x and y variables as those values, just use a third variable:

for (int z = 1; z < M+N; z++) {
    /* Some work */
    (x>0)?x--:y++;
}

Hope this helps!

Jack

like image 21
Jack Christmas Avatar answered Sep 20 '22 19:09

Jack Christmas