Exercise 10: Two Sided Steps - Pyramids

Directions

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

Examples

pyramid(1)
      '#'
  pyramid(2)
      ' # '
      '###'
  pyramid(3)
      '  #  '
      ' ### '
      '#####'

Guidelines

Two solutions:

  • Pseudo Code

03_14

Tip: round to nearest integer using Math.floor()

03_15

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 " "?

Solution

In [1]:
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);
  }
}

Alternative Solution: Recursion

In [2]:
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);
}
In [3]:
pyramid(1)
#
In [4]:
pyramid(2)
 # 
###
In [5]:
pyramid(3)
  #  
 ### 
#####