Repeat a string repeat a string using recursion

Repeat a string repeat a string using recursion
0.0 0

#1

Hello,

So this is my first attempt at this algorithm and I’ve done a bit of work with recursion in Java (not javascript) and I figured I would give it a go. My script appears to work in as much that it returns the correct results, but FCC won’t let it pass any of the tests. Well, sort of. Sometimes, when I press ctrl+enter it will pass the first test, and then other times, with no changes to the script, it won’t.

Here’s my code :

var out = ‘’;
function repeatStringNumTimes(str, num) {
// repeat after me

if (num<=0) {`
return out+’’;
} else {
out += str;
repeatStringNumTimes(str,num-1);
}

return out;
}

repeatStringNumTimes("*", 8);

I had thought that maybe it’s because I was using a global variable but that still doesn’t explain why sometimes it works for one of the tests and other times it doesn’t.

Anyone able to shed any light on this for me?

Thanks!
Bob


#2

It is because of the global variable but I don’t really know why it sometimes works for you. I can’t reproduce this result. Write a recursion that works without a global variable and it will pass.


#3

You know I had a horrible feeling it was the global variable giving me trouble. It felt like bad practice to use it but it just was a nice and easy solution. I’ll try something else! Thanks for the help!


#4

NP. There are two ways to fix it that I can think of. Let me know if you need help.


#6

Cool. So thanks P1xt I got your solution working quite quickly. Obviously put in an exception to cope with negative values. I then, tried to come up with a second solution based on what mkarabashev said, just to make it a challenge still, and came up with this that also works :

function repeatStringNumTimes(str, num) { // repeat after me

if (num<0) { return '';
} else if (num>1) { str += repeatStringNumTimes(str,num-1);
} return str;
}

Which I like because it’s got less lines and I think looks a bit tidier. :slight_smile:
Thanks for the help both of you!! :smiley:

P.S. So the markup thing doesn’t work the way I expect it to. I really wanted the code I posted to be all nicely formatted and all but the single quote marks need to be put on every other line and don’t do anything for indentation. Any helpful advice on how to do this? Or isn’t it that big a deal?


#7

To format you code block on the forum you can add put it in three backticks.

The format here is:
[three backtics]
codeblock
[three backticks]

Which then looks like this:

codeblock

How to post function result to button? [Solved]
#9

here’s an even more concise way to write it !

function repeatStringNumTimes(str, num) {
  if (num <= 0)
    return "";
  return str + repeatStringNumTimes(str, num - 1);
}

cheers


#10

An even more concise way to write it!

function repeatStringNumTimes(str, num) {
  return num <= 0 ? '' : str + repeatStringNumTimes(str, num - 1);
}