Javascript Steps Problem

The goal of this problem is to take in a number (example – 4, and then print out that number of steps).  There must be a space to pad out the rest of the character.  Ex. n=4; loop 1 will be one # and three spaces for a total of 4 characters:

#
##
###
####

I’m still working through Grider’s Udemy course on interview questions.  First I did it my own way that used two nested for loops.  I create an array called “step.”  Variable i loops through the number passed to the function (n=4 in the above illustration).  Variable j loops through and pushes the “#” symbol to the array based on the value of i.  Then the variable k loops through n-i times and pushes a ” ” to the array “step.”  Lastly, I use the join(“”) method to console log a string.  It’s not elegant, but it works.

// OPTION 1
function steps(n) {
   // console.log("function called");
   // console.log("n ", n);
   step = [];
   for (let i=1; i<=n; i++) {
      // console.log("i ", i);
      for (let j=1;j<=i; j++) {
         // console.log("j ", j);
         step.push("#");
      }
      for (let k=1; k<=n-i; k++) {
         // console.log("k ", k);
         step.push(" ");
      }
      console.log(step.join(""));
      step = [];
   }

}

Option 2 –  This is a much simpler solution that uses a nested loop with the outside loop representing rows and the inside loop representing columns.  This looks at the problem as a grid.  If the column is <= row, it outputs a “#” otherwise, it outputs a ” “(blank space).

//OPTION 2

   for (let row=0; row<n; row++) {
      let stair = "";

      for (let column=0; column < n; column++) {
         if(column<=row) {
            stair += "#";
         } else {
            stair += " ";
         }
      }
      console.log(stair);
   }
}

Option 3 – Recursive Solution

// OPTION 3
function steps(n, row=0, stair = "") {
   if (n === row) {
      return;
   }

   if (n === stair.length) {
      console.log(stair);
      return steps(n, row+1);
   }

   if (stair.length <= row) {
      stair +="#";
   } else {
      stair += " ";
   }
   steps(n, row, stair);
}   

 

Comments Are Closed