0

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);

    } } }
2
  • 6
    Well, if you call that method with time being any multiple of 10 (or zero), it'll constantly call the climb(height+3, time+10); method, and you'll run out of stack. I.e., your recursion doesn't work. Commented Oct 17, 2013 at 5:46
  • what is the initial value of height and time. Commented Oct 17, 2013 at 5:52

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

OHHHH this actually worked! thannk youuu so much! I highly appreciate it ! :)
1

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.

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.