Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Suppose having three arrays:

char [] one = {'a','b','c'};
char [] two = {'1','2','3'};
char [] three = {'x','y','z'};

If I want to print them like this:

a 1 x
a 1 y
a 1 z

a 2 x
a 2 y
.....
c 3 z

I must create three nested loops;

for(char i : one)
  for(char j : two)
    for(char k : three)
       //.....

Suppose if I have 7 arrays, it will be 7 nested loops.

Is there a better way to do that or an API maybe? I know you're probably asking why you do such a thing, It's just the mater of thinking.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
132 views
Welcome To Ask or Share your Answers For Others

1 Answer

The trick is to use an array of indices. Update them like the odometer in a car: least significant index then if overflow set that to zero and move on to the next... When no overflow, the update is done. Go ahead and print. When there's an overflow of the last index, printing is done.

// Accept an array of character arrays and print a nest
// of their contents.
static void print(char [] [] a) {
    int n_arrays = a.length;
    int [] indices = new int[n_arrays];  // All set to 0 by java
    // Decrement so that first increment is to all zeros. Avoids test for empty arrays.
    indices[n_arrays - 1] = -1; 
    for (int j = 0;;) {
        // Increment indices.
        for (j = n_arrays - 1; j >= 0; j--) {
            if (++indices[j] >= a[j].length) {
                indices[j] = 0;
            }
            else {
                break;  // No overflow. Increment is complete.
            }
        }
        if (j < 0) {
            break; // Last index overflowed.  We're done.
        }
        // Print.
        for (int i = 0; i < n_arrays; i++) {
            System.out.print(a[i][indices[i]]);
        }
        System.out.println();
    }
}

// Varargs version.
static void printArgs(char [] ... a) {
    print(a);
}

static char [] one = {'a','b','c'};
static char [] two = {'1','2','3'};
static char [] three = {'x','y','z'};

public static void main(String[] a) {
    print(new char [] [] { one, two, three } );
    printArgs(one, two, three);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...