Created
June 14, 2022 20:51
-
-
Save harryWonder/3b176a60e3dea7acce6d3eeacff99a79 to your computer and use it in GitHub Desktop.
The staircase algorithm with javascript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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