How to display pyramid using JavaScript?

前端 未结 22 884
长情又很酷
长情又很酷 2020-11-29 11:45

Here is the code to display pyramid but its not exactly producing required output.

22条回答
  •  广开言路
    2020-11-29 12:10

    If we're talking about the 'pyramid' problem, then this would be an appropriate solution.

    function pyramid(n) { // If (e.g.) n=3;
      const columnLength = (n * 2) - 1; // 5 
      let middle = Math.floor(columnLength / 2) // middle would be 2
      for(let row=0; row row=2;col=3; row=3;col=5; row=5;col=9
    // We got 2 sides, right? 
    // So, before we insert '#' we need to make sure the following logic is met:
    // Look at:  (middle - row) as being the left side and  (middle + row) as the right one.
    // Only if both conditions are met, we want to insert the "#" sign
          if(middle - row <= col && middle + row >= col ) {
             res += '#';
          } else {
    // If '#' is NOT inserted then we want to insert something else, right?! 
    // In our case that would be an empty string
            res += ' ';
          }
        }
        console.log(res);
      }
    }
    
    pyramid(3);


    And if we want to be extra 'fancy, we coučld implement recursion:

    function recursiveP(n, row=0, res='') { // IMPORTANT: Pass some default values
          const columnLength = (n * 2) - 1;
          let middle = Math.floor(columnLength / 2);
          // This is our EXIT condition, meaning, if have the n number of rows, our work is done!!
          if(n === row) {
            return;
          }
          //  *** Moving on ***
          //   Initially, this will be skipped, and we'll go to the next check and add the appropriate character,
          //   however, after we're finished w/ creating the 1st row we'll hit this check, we'll print the previously generated result,
          //   and call the function again, but this time incrementing the ROW value. This will continue until the 1st check is met
          if(res.length === columnLength) {
             console.log(res);
             return recursiveP(n, row + 1);
          }
          //   Here we're creating the columns and in each, we're inserting the appropriate char
          if(middle - row <= res.length && middle + row >= res.length ) {
             res += '#';
          } else {
             res += ' ';
          }
          //Initial [recursive] function call
          recursiveP(n, row, res);
        }
        
        recursiveP(6);

提交回复
热议问题