Write a function that accepts a positive number N. The function should console log a pyramid shape with N levels using the # character. Make sure the pyramid has spaces on both the left and right hand sides
pyramid(1)
'#'
pyramid(2)
' # '
'###'
pyramid(3)
' # '
' ### '
'#####'
Two solutions:
Tip: round to nearest integer using Math.floor()
How n is related to num of columns (n,col)? (1,1) (2,3) (3,5) (4,7) (5,?)
Within each row, how to determine which col is "#" or " "?
function pyramid(n) {
// get the mid-point index of the row
const midPoint = Math.floor((2*n - 1)/2);
for (let row = 0; row < n; row++){
let str = "";
for (col = 0; col < 2*n - 1 ; col++){
// current col is within thr range of mid-point
if (midPoint - row <= col && midPoint + row >= col){
str += "#";
} else {
str += " ";
}
}
console.log(str);
}
}
function pyramid(n, row = 0, str = "") {
if (row === n){
return;
}
if (str.length === 2*n -1){
console.log(str);
return pyramid(n, row + 1);
}
const midPoint = Math.floor((2*n - 1)/2);
let add;
if (midPoint - row <= str.length && midPoint + row >= str.length){
add = "#";
} else {
add = " ";
}
pyramid(n, row, str += add);
}
pyramid(1)
pyramid(2)
pyramid(3)