freeCodeCamp Algorithm Challenge Guide: Repeat a string repeat a string

freeCodeCamp Algorithm Challenge Guide: Repeat a string repeat a string
0

#1

:triangular_flag_on_post: Remember to use Read-Search-Ask if you get stuck. Try to pair program :busts_in_silhouette: and write your own code :pencil:

:checkered_flag: Problem Explanation:

The program is very simple, we have to take a variable and return that variable being repeated certain amount of times. No need to add space or anything, just keep repeating it into one single string.

Relevant Links

:speech_balloon: Hint: 1

You can’t edit strings, you will need to create a variable to store the new string.

try to solve the problem now

:speech_balloon: Hint: 2

Create a loop to repeat the code as many times as needed.

try to solve the problem now

:speech_balloon: Hint: 3

Make the variable created store the current value and append the word to it.

try to solve the problem now

Spoiler Alert!

687474703a2f2f7777772e796f75726472756d2e636f6d2f796f75726472756d2f696d616765732f323030372f31302f31302f7265645f7761726e696e675f7369676e5f322e676966.gif

Solution ahead!

:beginner: Basic Code Solution:

function repeatStringNumTimes(str, num) {
  var accumulatedStr = '';

  while (num > 0) {
    accumulatedStr += str;
    num--;
  }

  return accumulatedStr;
}

:rocket: Run Code

Code Explanation:

  • Create an empty string variable to store the repeated word.
  • Use a while loop or for loop to repeat code as many times as needed according to num
  • Then we just have to add the string to the variable created on step one, and increase or decrease num depending on how you set the loop.
  • At the end of the loop, return the variable for the repeated word.

Relevant Links

:sunflower: Intermediate Code Solution:

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

:rocket: Run Code

Code Explanation:

  • This solution uses recursion.
  • We check if num is negative and return an empty string if true.
  • Then we check if it’s equal to 1 and in that case we return the string itself.
  • If not, we add the string to a call of our function with num being decreased by 1, which will add another str and another… until eventually num is 1. And return that whole process.

Relevant Links

:rotating_light: Advanced Code Solution:

function repeatStringNumTimes(str, num) {
  return num > 0 ? str.repeat(num) : '';
}

repeatStringNumTimes("abc", 3);

:rocket: Run Code

Code Explanation:

  • This solution takes a declarative approach.
  • It is similar to the third solution, except it uses the ternary operator form of the if statement.

Relevant Links

:clipboard: NOTES FOR CONTRIBUTIONS:

  • :warning: DO NOT add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.
  • Add an explanation of your solution.
  • Categorize the solution in one of the following categories — Basic, Intermediate and Advanced. :traffic_light:
  • Please add your username only if you have added any relevant main contents. (:warning: DO NOT remove any existing usernames)

See :point_right: Wiki Challenge Solution Template for reference.


Repeat a string challenge - Tips please
Repeat a string repeat a string - part duex
#2

#3

#4

I used an array method, I would say it was a beginner way to do it.

function repeatStringNumTimes(str, num) {
var strArray=[];

for(i=0;i<num;i++){strArray.push(str);}
return strArray.join("");
}


#5

I used a bit different code and it worked fine:

function repeatStringNumTimes(str, num) {
// repeat after me
if (num > 0) {
return str.repeat(num);
} else {
return “”;
}
}


#6

function repeatStringNumTimes(str, num) {
// repeat after me
repeat = “” ;
for (;num > 0;repeat += str,num–){}
return repeat;

}

repeatStringNumTimes(“abc”, 3);


#7

i have solved this like below…

function repeatStringNumTimes(str, num) {
  // repeat after me
  var repeat="";
  for (var i = 1; i<=num ; i++){
      repeat = repeat.concat(str);
  }
  return repeat;
  
}

repeatStringNumTimes("myName", 4 );

is there any problem in this way of approach for solving this problem


#8

Can someone explain why this didn’t work:

function repeatStringNumTimes(str, num) {
  var re_peat = str.repeat(num);
	if (num >= 0){
  return re_peat;
	} else {
		return "";
	}
}

why can’t you store the method in a variable?
but this worked just fine:

function repeatStringNumTimes(str, num) {
  //var re_peat = str.repeat(num);
	if (num > 0){
    return str.repeat(num);
  
	} else {
   
		return "";
	}
}

Thank you in advance.


#9

The advanced method here uses the repeat method…which is the best way but the challenge said not to for some reason…to make us work i guess.

i came up with.

function repeatStringNumTimes(str, num) {
return (num<1) ? "": str.concat(repeatStringNumTimes(str,num-1));}

its just a spruced up version of the intermediate code. it uses concat instead of a plus sign and ternary operators. done this way its not much longer than using repeat.


#10

That’s my code:

function repeatStringNumTimes(str, num) {

  var strRepeated = "";
  
    for(var i=0; i<num; i++){
      strRepeated +=  str;
    }

   return strRepeated;
}

//test
repeatStringNumTimes("*", 2);

#11

I noticed that a few people posted solutions that are VERY SIMILAR to the FCC solution, but using for loops with decalred var i rather than while loops incrementing num itself. @TatheerHussain @irakligeek

I ran some performance tests, and I found that using a for loop instead of a while loop takes almost TWICE as long! question is: why? is it because you are declaring a second variable in the for loop? is it that much faster just to use num instead of introducing i as well? or is there something about the difference between the two loops that I don’t understand?

1,000,000 repetitions of each function
with for loop and var i: 64.7 milliseconds
with while loop and incrementing num: 34.2 milliseconds

10,000,000 repetitions of each function
with for loop and var i: 562.6 milliseconds
with while loop and incrementing num: 313.6 milliseconds

100,000,000 repetitions of each function
with for loop and var i: 5.5 seconds
with while loop and incrementing num: 3.09 seconds

1,000,000,000 repetitions of each function
with for loop and var i: 54.8 seconds
with while loop and incrementing num: 30.7 seconds


#12

I solved this challenge with this:

function repeatStringNumTimes(str, num) {
// repeat after me
var more = ‘’;
for(var i = 0; i < num; i++){
if(num > 0){
more += str;
}else{
return ‘’;
}
}
return more;
}

repeatStringNumTimes(“abc”, 1);


#13

Basicly your top solution doesn’t work because the repeat function only allows values >= 0.
If num is negative it evaluates to an error : Uncaught RangeError: Invalid count value , and therefor JavaScript
wont progress.

So basicly the 2nd solution is the correct way, but you could have solved it that way too:

// store the function in re_peat with (str,num) parameters and return the result of str.repeat(num)
var re_peat = function (str, num) {
return str.repeat(num);
};

// still check if num > 0 to call the function with the Parameters, because see reason above.
if (num > 0)
{
return re_peat(str,num);
}
else
{
return “”;
}

Hope that helped.


#14

USING A FOR LOOP:
function repeatStringNumTimes(str, num) {
// repeat after me
var a="";
if (num>0)
{
for(i=1;i<=num; i++){
a += str;
}

}
return a;
}

repeatStringNumTimes("$", 32);


#15

function repeatStringNumTimes(str, num) {
var texto ="";
if(num<0){
str = “”;
} else {
for(var i=0;i<num;i++){
texto+=str;
}
}
return texto;
}

repeatStringNumTimes(“abc”, 3);


#16
function repeatStringNumTimes(str, num) {
  
  // repeat after me
  if (num <= 0) return "";
  
  return new Array(num+1).join(str);
}

#17

I solved it this way, but thanks to @jmbothe, I’ll switch to while loops going forward.

function repeatStringNumTimes(str, num) { var newString = ''; // repeat after me for (i = 0;i < num; i++) { newString = newString + str; } return newString; } repeatStringNumTimes("abc", 3);


#18

My solution ended up being an unoptimized version of advanced code solution using repeat method

function repeatStringNumTimes(str, num) {
  
  //Positive num only
  if (num <= 0){
    return "";
  }
  
  return str.repeat(num);
}

repeatStringNumTimes("abc", 3);

#19

This is how I solved it. The str.repeat pretty much solved the issues for me.


#20

The code I wrote seems to get the correct answer but the page wont recognise me passing. Any idea?

acc = “”;

function repeatStringNumTimes(str, num) {
if (num > 0) {
for (i = 0; i != num; i++) {
acc += str;
}
return acc;
}
return “”;
}

repeatStringNumTimes(“abc”, 3);