** It's a story **
Not limited to Java, when writing a program, there are times when you have to write multiple for loops.
Example. I want to set all the elements of an int type 3D array to 1.
final int n = 10;
final int[][][] cube = new int[n][n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
cube[i][j][k] = 1;
}
}
}
However, such a loop causes deep nesting and unnecessary increase in the number of lines, which causes the maintainability of the program to deteriorate. Therefore, let us consider a method to make multiple for loops single.
To solve the problem, first check the syntax of the for loop. [Eclipse JDT](https://help.eclipse.org/2019-12/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjdt%2Fcore%2Fdom% According to 2FEnhancedForStatement.html), the for statement has the following structure.
for ( [ ForInit ]; [ Expression ] ; [ ForUpdate ] ) Statement
In addition, ForInit and ForUpdate are defined as follows.
ForInit: Expression { , Expression } ForUpdate: Expression { , Expression }
Since ForInit and ForUpdate can specify multiple expressions, it seems possible to write variable updates in ForUpdate with the declaration of each variable required in multiple for loops in ForInit.
Now, let's actually make a single for loop.
In the previous example, there are three required variables, ʻi, j, k`, so the initialization formula is
int i = 0, j = 0, k = 0
It seems to be okay.
Next is the (end) conditional expression. In this case, ʻi that controls the outermost loop regardless of the value of j, k`
i < n
Can be written as.
Finally, let's think about the update formula.
Think in order (k-> j-> i) from the variables that control the inside of the loop.
First of all, regarding k, it should be incremented every time the loop is made, and it should be 0 when the value of k becomes n.
k = (k + 1) % n
Can be written.
Next, regarding j, the update timing of j is the timing when k becomes 0, and the value does not change otherwise.
j = k == 0 ? (j + 1) % n : j
It becomes.
Finally, ʻi, but the update timing is k == 0 && j == 0`
i = j == 0 && k == 0 ? i + 1 : i
is.
When the results so far are integrated, it can be rewritten as follows.
final int n = 10;
final int[][][] cube = new int[n][n][n];
for (int i = 0, j = 0, k = 0; i < n; k = (k + 1) % n, j = k == 0 ? (j + 1) % n : j, i = j == 0 && k == 0 ? i + 1 : i) {
cube[i][j][k] = 1;
}
Compared to the code of the first triple loop, the nesting is reduced, and it seems to be a neat impression.
This time, I introduced how to convert multiple for loops to single loops. Please use this as a reference to improve the readability of your code!
Recommended Posts