简体   繁体   中英

Can I split this two-variable for loop into two nested loops?

I would like to know about the given for loop which looks weird to me:

for (int i = 0, j = s.length - 1; i < j; i++, j--)

So far, I was using for loop with one variable. However in this example there are two variables within one loop.

Can I split the for loop into two nested loops?

for (int j = 0; j < s.length - 1; j--) {
    for (int i = 0; i < j; i++) {
    }
}

it is wrong conversion, correct one will be:

int j = s.length - 1;
for (int i = 0; i < j; i++) {
    // inside logic
    j--;
}

No.
The original acts like this:

sssssss
i     j

sssssss
 i   j

sssssss
  i j

sssssss
   i
   j

It has for example (s.length)/2 iterations. And iterates over one half with i and the other half with j.

The proposed alternative is 2D and has for example (s.length*s.length)/2 iterations (and that is assuming j++ instead of the broken j-- ). It covers something of a triangle.

sssssss
j
ij
iij
iiij
iiiij
iiiiij
iiiiiij

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM