This forum is now read-only. Please use our new forums at discuss.codecademy.com.

Big O Forum

View Course » View Exercise

1707 points
350c0824be8464439f823d7d0e4bfc92?s=140&d=retro
Submitted by
Jonathan S
over 4 years ago

Exercise freezes up, and I don't have any infinite recursion going on

This is the code I was using:

// Function to recursively print the right half of a string
    var right = function(str){
    var length = str.length;

    // Helper function
    var help = function(index){

        // Recursive Case: Print right half
        if(index < length ){
            // Prints characters from index until the end of the array
            console.log(str.substring(index, length));

            // Recursive Call: call help on right half
            help((length - Math.ceil((length-index)/2)));
        }

        // Base Case: Do Nothing
    };

    help(0);
};

// Testing
var word = "question";
right(word);

I think this matches the code that other people had in the other question on this topic http://www.codecademy.com/forum_questions/4fbd2b47ad12130003000161. Whenever I hit run, it acts like the browser is about to freeze up, and eventually I get the "Kill/Wait" dialog from Chrome.

I don't think my code is going into infinite recursion, but it's possible I'm overlooking something. Obviously, we can't solve the halting problem, but it might be nice if the run button checked the parameters in the if statement and recursive function against the sample before running the code, maybe?


1 vote

permalink

Think about the parameter you pass to the helper function. Is Math.ceil() the right function to use? Will the parameter ever be >= length in your example? Try doing it out on paper to see an illustration of this.

389 points
4f8f6ea95a87fe00030031ad_732049700
Submitted by
Eric Summers
over 4 years ago

2 Comments

350c0824be8464439f823d7d0e4bfc92?s=140&d=retro Jonathan S over 4 years ago

I thank you very much! (and I chastise myself for ignoring the important "desk check").

350c0824be8464439f823d7d0e4bfc92?s=140&d=retro Jonathan S over 4 years ago

IMHO, the exercise could use a hint in this regard.