1

I have a problem with nested for loops in java. My problem is that at the beginning I don't know exactly how many for loops I will need. It is set somewhere in the middle of my program. So let say my program creates an array. If the array has 3 elements then I create a three for loops like below.

for(int i = 0; i<tab[0].length() ; i++){
    for(int j = 0; j<tab[1].length() ; j++){
        for(int k = 0; k<tab[2].length() ; k++){
            System.out.println(i+" "+j+" "+k);
        }
    }
}

If my program created an array with 4 elements then it would be like this:

for(int i = 0; i<tab[0].length() ; i++){
    for(int j = 0; j<tab[1].length() ; j++){
        for(int k = 0; k<tab[2].length() ; k++){
             for(int h = 0; h<tab[3].length() ; h++){
                System.out.println(i+" "+j+" "+k+" "+h);
             }
        }
    }
}

Can any one tell me how to do this with recursion? I can have 2 nested loops but I can have 10 of them and always at the end I would like to print in the console numbers associated with all loops (i,j,k,h)

1 Answer 1

3

Here is a solution. At each recursive call, previousTabs becomes 1 longer and tabs becomes 1 shorter.

public static void iterate(int[] previousValues, int[] tabs) {
    if (tabs.length == 0) {
        System.out.println(Arrays.toString(previousValues));
    }
    else {
        final int[] values = new int[previousValues.length + 1];
        for (int i = 0; i < previousValues.length; i++) {
            values[i] = previousValues[i];
        }
        final int[] nextTabs = new int[tabs.length - 1];
        for (int i = 0; i < nextTabs.length; i++) {
            nextTabs[i] = tabs[i + 1];
        }
        for (int i = 0; i < tabs[0]; i++) {
            values[values.length - 1] = i;
            iterate(values, nextTabs);
        }
    }
}
public static void iterate(int[] tabs) {
    iterate(new int[0], tabs);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.