Last active
March 8, 2023 02:08
-
-
Save GreggSetzer/173fdba432038eb9c0fdaeddbdb2f936 to your computer and use it in GitHub Desktop.
Javascript Interview Question: Stairs
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
/* | |
A simple iterative solution to building steps. | |
Uses String.prototype.repeat which is an ES2015 feature. | |
*/ | |
function steps(n) { | |
for (let i = 1; i <= n; i++) { | |
let step = '#'.repeat(i) + ' '.repeat(n - i); | |
console.log(step); | |
} | |
} | |
//Try it | |
steps(5); |
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
/* | |
Create a stair case. | |
Pseudo Code: | |
To create a staircase, | |
Draw a grid to visualize the question. | |
'# ' | |
'## ' | |
'### ' | |
'####' | |
For rows 0 to n | |
- Create a string variable to hold the characters that make up the step. | |
- For cols 0 to n | |
- Check if the col is less than or equal to row. | |
- If so print a #. | |
- Otherwise, print a space. | |
*/ | |
function steps(n) { | |
for (let row = 0; row < n; row++) { | |
let step = ''; | |
for (let col = 0; col < n; col++) { | |
step += (col <= row) ? '#' : ' '; | |
} | |
console.log(step); | |
} | |
} | |
//Try it | |
steps(5); | |
/* | |
Create a stair case using recursion. | |
First, determine the base case. Base case can be found in the first for loop. Once the | |
row === n, the base case condition has been met. Exit function. | |
Second, determine when we are at the end of a row. If that condition is met, print the step to | |
the console, call the steps function with arguments: (a) n, (b) row + 1. Call return here. | |
Third, append the # or space character. Call the steps function with three arguments: (a) n, (b) row, and (c) step. | |
Note: | |
We can replace the col variable from the first example with step.length. They mirror each other | |
which means we do not need to track the col varaible. | |
For any arguments we provide other than n (n is required), we can assume a reasonable default | |
and initialize the variable in the function signature. | |
*/ | |
function steps(n, row = 0, step = '') { | |
//Base case. | |
if (n === row) { | |
return; | |
} | |
//Is it time for a new row? | |
if (n === step.length) { | |
console.log(step); | |
steps(n, row + 1); | |
return; | |
} | |
//Append a character. | |
step += (step.length <= row) ? '#' : ' '; | |
steps(n, row, step); | |
} | |
steps(5); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment