[Java] How to make multiple for loops single

** It's a story **

Introduction

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.

for loop syntax

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.

I tried it

Now, let's actually make a single for loop.

Initialization formula

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.

Conditional expression

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.

Renewal formula

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.

result

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.

in conclusion

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

[Java] How to make multiple for loops single
Java --How to make JTable
How to make a Java container
How to make a Java array
How to make a Java calendar Summary
How to make a Discord bot (Java)
How to switch between multiple Java versions
[Java] How to test for null with JUnit
How to make a lightweight JRE for distribution
How to make shaded-jar
[Java] (for MacOS) How to set the classpath
How to make Java unit tests (JUnit & Mockito & PowerMock)
[For beginners] How to operate Stream API after Java 8
How to use Truth (assertion library for Java / Android)
How to make Laravel faster with Docker for Mac
How to make a mod for Slay the Spire
How to loop Java Map (for Each / extended for statement)
How to execute WebCamCapture sample of NyARToolkit for Java
How to lower java version
[Java] How to use Map
How to use java Optional
How to minimize Java images
How to write java comments
How to use java class
[Java] How to display Wingdings
[Java] How to use string.format
How to use Java Map
How to set Java constants
How to use Java variables
How to convert Java radix
[Java] How to use Optional ①
How to initialize Java array
How to use SAS tokens for Azure Event hubs (Java)
[Must-see for apprentice java engineer] How to use Stream API
How to create a lightweight container image for Java apps
How to make th: value of select have multiple values
For Java beginners: List, Map, Iterator / Array ... How to convert?
Operation to connect multiple Streams @Java
How to specify validation for time_field
How to install JMeter for Mac
Studying Java # 6 (How to write blocks)
[Java] How to update Java on Windows
How to disassemble Java class files
How to use Java HttpClient (Post)
[Java] How to use join method
How to make a JDBC driver
How to learn JAVA in 7 days
[Processing × Java] How to use variables
[Java] How to create a folder
How to decompile java class files
[Java] How to use LinkedHashMap class
[JavaFX] [Java8] How to use GridPane
How to write Java variable declaration
How to make a splash screen
How to make a Jenkins plugin
How to use class methods [Java]
[Java] How to use List [ArrayList]
How to use classes in Java?
How to make a Maven project
How to name variables in Java
How to pass Oracle Java Silver