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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With