简体   繁体   中英

How to use recursive function in place of nested loops?

I want code such that I get two input from the user, one the variable n and the second is the variable t where 1<=n<=4. I want to make n nested loops in which every loop run for t times. I have made a code to do this in Java:

int n=in.nextInt();
int t=in.nextInt();
for(int l1=1;l1<=n;l1++)
{
    if(n==1)
    {
        //do something here
    }
    else
    {
        for(int l2=11;l2<=m;l2++)
        {
            if(n==2)
            {
                //do something here
            }
            else
            {
                for(int l3=1;l3<=t;l3++)
                {
                    if(n==3)
                    {
                        //do something here
                    }
                    else
                    {
                        for(int l4=1;l4<=t;l4++)
                        {
                            //do something here
                        }
                    }   
                }
            }
        }
    }
}

But here, if i want n in range 1<=n<=10, then I have nest loop 10 time, which is not a good idea. What is better approach to do this. Here,"do something here" is same in each case. Thanks in advance.

We can make a recursive function like I have made. In my recursive function, I have passed to arguments, first is int n and second is int t. n represents how much nested loops we want and for how much iteration and t represents at what iteration is the function running.

    public static void recursive(int n,int t)
    {
        for(int i=1;i<=n;i++)
        {
            if(n==t)
                //do something here
            else
                recursive(n,t+1);
        }
    }

This worked perfectly for me.

Something like that should do:

interface Op { public void apply(); }

void f(int start, int end, int crucialStep, Op doSomething) {
    for (int i = start; i <= end; i++) {
        if (i == crucialStep) { doSomething.apply(); }
        else { f(1, 10, crucialStep + 1, doSomething); }
    }
}

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