Recursive implementation of loops with unknown times

Source: Internet
Author: User

The following example:

public class Test4 {public

    static void Main (string[] args) {

        int m = ten;
        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+ "," +j+ "," +k+ "," +l+ "]");}}}}}


If the number of nested loops is specified dynamically, it cannot be achieved by the way above, which can only work if the number of nested loops is determined.

How to break, using recursion can skillfully solve the above scenario, the code is as follows:

Import Java.util.Arrays;

public class test5{public

    static void Main (string[] args) {
        recurse (new int[] {5, 2, 4}, new Int[3], 0);
    } Public


    static 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]) {
                    C Ontinue outer;
                }
            }
            B[depth] = i;
            Recurse (A, B, depth + 1);}}}


As you can see by comparison, the code that is implemented recursively is very concise and elegant, but it is also very inefficient, especially when the number of loops and the depth of nesting are large.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.