嵌套循环执行

时间:2015-05-31 05:50:33

标签: algorithm loops for-loop printing

这是一个非常简单的问题,但由于某种原因,我感到困惑,而且很烦人。

def test():
for i from Lo1 to Hi1:
    for j from Lo2 to Hi2:
    body()

body()执行的次数为: Lo1 = 1,Hi1 = n,Lo2 = i-2,Hi2 = i + 2

答案是5n次,但我不知道他们是怎么得到的!

3 个答案:

答案 0 :(得分:3)

Lo2 = i-2,Hi2 = i + 2 内环

  

所以(i-2)到(i + 2)= 5轮换EG: i-2 , i-1 , i , i+1 , i+2

     

赞(-2)到(+2)= - 2,-1,0,1,2

Lo1 = 1,Hi1 = n 外环

  

1到N

总计 Inner* Outer

  

5 * N = 5N

答案 1 :(得分:1)

我认为最简单的理解方法就是运行它。

例如对于n=10,以下java代码在每次迭代中打印ij的值:

 for (int i=0; i<=10; i++){
     for (int j=i-2; j<=i+2; j++)
         System.out.println("i = " + i + ", j= " + j);
 }

结果如下:

i = 0, j= -2
i = 0, j= -1
i = 0, j= 0
i = 0, j= 1
i = 0, j= 2
i = 1, j= -1
i = 1, j= 0
i = 1, j= 1
i = 1, j= 2
i = 1, j= 3
i = 2, j= 0
i = 2, j= 1
i = 2, j= 2
i = 2, j= 3
i = 2, j= 4
i = 3, j= 1
i = 3, j= 2
i = 3, j= 3
i = 3, j= 4
i = 3, j= 5
i = 4, j= 2
i = 4, j= 3
i = 4, j= 4
i = 4, j= 5
i = 4, j= 6
i = 5, j= 3
i = 5, j= 4
i = 5, j= 5
i = 5, j= 6
i = 5, j= 7
i = 6, j= 4
i = 6, j= 5
i = 6, j= 6
i = 6, j= 7
i = 6, j= 8
i = 7, j= 5
i = 7, j= 6
i = 7, j= 7
i = 7, j= 8
i = 7, j= 9
i = 8, j= 6
i = 8, j= 7
i = 8, j= 8
i = 8, j= 9
i = 8, j= 10
i = 9, j= 7
i = 9, j= 8
i = 9, j= 9
i = 9, j= 10
i = 9, j= 11
i = 10, j= 8
i = 10, j= 9
i = 10, j= 10
i = 10, j= 11
i = 10, j= 12

您现在可以看到10i次迭代,而i5j(from i-2 to i+2)次迭代50 (5*N)。因此总共- (IBAction)pushToSearch:(id)sender{ SearchModalViewController *searchModal = [self.storyboard instantiateViewControllerWithIdentifier:@"search"]; searchModal.searchDelegate = self; [self presentViewController:searchModal animated:YES completion:nil]; } 次迭代。

答案 2 :(得分:1)

假设有一个带有Java代码的for循环

for(int i=3;i<=6;i++)
{
    //Statements to be executed
}

循环将执行4次(i = 3,4,5,6)

如何计算?

公式=上限 - 下限+ 1

所以在上面的循环中它将是6-3 + 1 = 4(上限= 6,下限= 3)

在你的问题中 上限= i + 2

下限= i-2

内循环执行的总次数= i + 2-(i-2)+ 1 = i + 2-i + 2 + 1 = 5

外部循环将执行n次,因此只需乘以n

因此答案变为5 * n = 5n