Skip to content

Instantly share code, notes, and snippets.

@harryWonder
Created June 14, 2022 20:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harryWonder/3b176a60e3dea7acce6d3eeacff99a79 to your computer and use it in GitHub Desktop.
Save harryWonder/3b176a60e3dea7acce6d3eeacff99a79 to your computer and use it in GitHub Desktop.
The staircase algorithm with javascript.
/**
* Determine the number of stairs to print
* The default stair has to have at least 1 space from the left
* Other stairs should inherit the same syntax except the last one
*
* First thing I had to do was initalize an empty stairs.
* Create a loop based on the stairCaseLength Param.
* Initialize two indexes. (One to handle the loop from 0 - stairCaseLength)(i) and the other to (decrement the stairCaseLength)(j)
* For each case to be printed to the console, I had to use the .repeat method with (j - 1) to print the number of spaces the stairs(#)(i) should have. This would in turn make sure that the last stair to be printed has no spacing.
* The stairs denoted by (#) are also printed out using the repeat method and it takes the (i + 1) as a param.
*
* @param {number} stairCaseLength
*
*/
function StairCase(stairCaseLength) {
let stairs = "";
for (let i = 0, j = stairCaseLength; i < stairCaseLength; i++, j--) {
let stair = " ".repeat(j - 1) + "#".repeat(i + 1) + "\n";
stairs += stair;
}
console.log(stairs.trimEnd());
}
StairCase(14);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment