Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iteration counter for double loops

I am trying to find the formula to count every iteration of this double for loop (in python for instance):

for i in range(5):
   for j in range(5):
       count = MYSTERIOUS_FORMULA
       print count

Here the final value of count should be 25.

I tried count=(i+1)*j but it produce 0,1,2,3,4,0,2,4 etc.

like image 854
SdFRO0QS78 Avatar asked Apr 27 '17 14:04

SdFRO0QS78


1 Answers

The mysterious formula is quite simple:

{count} = {index of current loop} + {size of current loop}*{count of parent loop}

As an example, consider a single loop:

x = 5

for i in range(x):
    count = i

To be explicit, count = i + x*0 but the second term is irrelevant because there is no parent loop. An example of two loops might be more illuminating:

x = 5
y = 6

for i in range(x):
    for j in range(y):
        count = j + y*(i)

Notice that I put i in parentheses to emphasize that it is the {count of parent loop}. This formula can be easily expanded to a third loop:

x = 5
y = 6
z = 7

for i in range(x):
    for j in range(y):
        for k in range(z):
            count = k + z*(j + y*(i))

and so on...

like image 54
Splic Avatar answered Nov 15 '22 04:11

Splic