简体   繁体   中英

Way to automate LOADS of nested for-loops? (Java)

I have a 3D integer array of length [9][3][3]. Every element in the array is initialised at a value of 1.

I want the very last element of the array (ie [8][2][2]) to cycle through all values 1 through 9. Then I want that same element to cycle through them again, for every time the element before it (ie [8][2][1]) increases by 1 up until 9. Likewise THIS element cycles through all values 1-9 for every increase of the previous element [8][2][0]. The only thing I can think if is manually setting up 81 nested for-loops, but this would take forever and is incredibly inefficient. I'm sure there's a better way.

Sorry if I'm not very good at explaining myself. Basically let's suppose this 3D array were output entirely in one line. At first it would look something like this:

111111111111111111111111111111111111111111111111111111111111111111111111111111111

Then I want that last digit on the right to repeatedly cycle through 1-9, and every time that happens, the one immediately to the left of it increases by 1. Then when THAT one reaches 9, the one to the left of it increases by 1. And so on. Repeat for all 81 elements of the array.

What's a better way to do this rather than 81 nested for-loops?

I apologise for any inaccuracy of terminology or lack of clarity. I'm self taught and rubbish at explaining myself.

This is like a complex version of incrementing an 81-digit base-9 number, but here it is. As mentioned in comments, you might go on with your life while waiting for it to complete.

public static void main(String[] args) {
    int[][][] data = new int[9][3][3];
    for (int x = 0; x < 9; x++)
        for (int y = 0; y < 3; y++)
            for (int z = 0; z < 3; z++)
                data[x][y][z] = 1;
    print(data);

    OUTER: while (true) {
        int x = 8, y = 2, z = 2;
        while (true) {
            if (data[x][y][z] < 9) {
                data[x][y][z]++;
                break;
            }
            data[x][y][z] = 1;
            if (--z < 0) {
                z = 2;
                if (--y < 0) {
                    y = 2;
                    if (--x < 0)
                        break OUTER;
                }
            }
        }
        print(data);
    }
}
private static void print(int[][][] data) {
    for (int x = 0; x < 9; x++)
        for (int y = 0; y < 3; y++)
            for (int z = 0; z < 3; z++)
                System.out.print(data[x][y][z]);
    System.out.println();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM