What is the infamous staircase problem?
Imagine a staircase. Each step takes you further from the first one. Simple enough, right?
The base and height both equal n
; # symbols and spaces represent each level of stairs. Your code should return a staircase of n
size.
Conditions
- n is an integer that represents the
size
of the staircase ie:n = 3
- Print the staircase size with
spaces
and#.
- sample:
#
##
###
Start Simple
We know that as we travel down the staircase, we need to reduce the number of spaces by 1. We also needed to keep track of each row to reduce the number of spaces.
Let's start with something simple(and ugly)...
function staircase(n) {
let row = "";
for (let j = n; j > 0; j--) {
for (let i = 1; i <= n; i++) {
if (i < j) {
row += " ";
continue;
}
row += "#";
} if (j === 1) {
continue;
}
row += "\n";
}
console.log(row);
}
The break down:
- I created a variable called
row
that will return the final result - The first(outer) loop tracks the number of rows
n
, that we need. - The second (inner) loop, tracks the number of spaces and # symbols needed for each row.
- Lastly, we output the result with a
console.log
.
The refactor
While the above code meets all the problem requirements, it's messy. So I did some research and found a much cleaner solution by Ali Reubenstone that uses JavaScript's repeat method.
function staircase(n) {
for (let i = 1; i <= n; i++) {
console.log(" ".repeat(n-i) + "#".repeat(i))
}
}
Let's break it down:
- The for loop iterates over each row.
- During the interation process, we print the # symbols and spaces.
- Finally, we repeat the blank spaces by the
n-i
number and # symbols by 'i' number of times so that each row (from top to bottom) reduces the number of spaces while increasing the number of # symbols, thus creating astaircase
shape.
Top comments (0)