问题
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