简体   繁体   中英

Recursive method and stack overflow

Okay so I have an assignment to determine how long will it take to a monkey to climb a pole of x height. If ascends 10 ft. in 10 minutes and slips down 3 in 10 min while resting. When it reaches the top of the pole it stops, and climbs one feet per minute. This using recurssion, and my method is right so far, but I'm getting stack overflow and I do not know how to avoid it so im freakin out, any idea?

Thanks guys

public static long climb(long height, long time) {    //Recursive method

    if (height <= 0)     //base case
        return time;

/*Every 10 min add 3 to height (notice im doing it backwards, 
instead of substracting 3.
I find it easier to deal with this way and easier to implement the base case) *//

    else if (time != 0 && time % 10 == 0) {    

        return climb(height+3, time+10);
    }

    else  {
        return climb(height-1, time+1);

    } } }

You can't do it like that. You might have problems with this two lines:

else if (time != 0 && time % 10 == 0) {    

    return climb(height+3, time+10);
}

If you're having the case that time is for example 10, you're adding 10 to the time-var and its finally 20, so 20 % 10 will result a true once again :)

Edit:\\

Damn, just a bit too late :)

Another edit:\\

To avoid this problem, add a reminder to the parameters:

    public static long Climb(long height, long time, bool justrested)
    {
        //Recursive method
        if (height <= 0)
        {
            //base case
            return time;
        }

        if(time%10 == 0 && !justrested)
        {
            return Climb(height + 3, time + 10, true);
        }

        return Climb(height - 1, time + 1, false);
    }

You can call it with now like that:

Climb(1800, 0, true);

Might be some mistakes in it, but hope its you anyway.

Stack error occurs when the memory is filled up, ie the problem here is that you don't have a working exit statement.

Try change this to long

if (height <= 0L) 

It would probably solve the issue.

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