How do I use the indices of nested for-loops to generate a consecutive list of numbers?

五迷三道 提交于 2020-01-15 07:37:27

问题


E.g.:

for (int i = 0; i < 3; i++) {
  for (int j = 0; j < 4; j++) {
    for (int k = 0; k < 5; k++) {
      ...
    }
  }
}

That's 3 * 4 * 5 = 60 times executing the innerst code. Now I want to use the values of the indices i, j, and k to generate all numbers from 0 to 59 (not necessarily sorted).


回答1:


Ok, got it.

Make k count 1, j count k's limit, i count j's limit times k's limit.

for (int i = 0; i < 3; i++) {
  for (int j = 0; j < 4; j++) {
    for (int k = 0; k < 5; k++) {
      int c = k * 1 + j * (5) + i * (5 * 4);
      System.out.println(c);
    }
  }
}

Output: 0..59.



来源:https://stackoverflow.com/questions/6604502/how-do-i-use-the-indices-of-nested-for-loops-to-generate-a-consecutive-list-of-n

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!