Search code examples
javarecursioncycle

How can the nested loops of unknown layers be implemented by recursion?


int m =10;

    int n = 9;

    int p = 4;

    int q = 7;

    for(int i=0;i<m;i++){

        int a = i;

        for(int j=0;j<n;j++){

            int b = j;

            if(b==a){

                continue;

            }

            for(int k=0;k<p;k++){

                int c = k;

                if(c==b || c==a){

                    continue;

                }

                for(int l=0;l<q;l++){

                    int d = l;

                    if(d==c || d==b || d==a){

                        continue;

                    }

                    System.out.println("i="+i+",j="+j+",k="+k+",l="+l);

                }

            }

        }

    }

For example, the code fragment is a four layer nested loop, and the loop between has data dependencies, and nested layers is uncertain, how it will achieve through the recursive (nested is uncertain)?


Solution

  • void recurse(int[] a, int[] b, int depth) {
        if (depth == a.length) {
            System.out.println(Arrays.toString(b));
            return;
        }
    
        outer:
        for (int i = 0; i < a[depth]; i++) {
            for (int j = 0; j < depth; j++) {
                if (i == b[j]) {
                    continue outer;
                }
            }
            b[depth] = i;
            recurse(a, b, depth + 1);
        }
    }
    

    Sample call:

    recurse(new int[] {10, 9, 4, 7}, new int[4], 0);