2

I am currently trying to solve the xmas tree problem, with internal tree-like shape.

issue is with internal spacing, it supposed to be like: 1, 5, 7, 9. Instead it is 1, 3, 4, 5. I do not know, how to increment s loop by 2 in each loop turn.

/*
*********
**** ****
***   *** 
**     **
*       *
*********
*/

function drawTree(h) {

  let n = h + 3;
  for (var i = 1; i <= 1; i++) {
    var temp = "";
    for (var j = 1; j <= n; j++) {
      temp = temp + "*";
    }
    console.log(temp);
  }

  for (var i = 0; i < h - 2; i++) {
    var tree = '';

    console.log("\n");

    for (var k = 3; k <= h - i; k++) {
      tree += "*";
    };

    tree += "s";

    for (var k = 1; k <= i; k++) {
      for (var k = 1; k <= i; k++) {
        tree += "s";
      };
      tree += "s";
    };

    for (var k = 3; k <= h - i; k++) {
      tree += "*";
    };

    console.log(tree);
  };

  console.log("\n");

  let g = h + 3;
  for (var i = 1; i <= 1; i++) {
    var temp = "";
    for (var j = 1; j <= g; j++) {
      temp = temp + "*";
    }
    console.log(temp);
  }

};
drawTree(6);
VLAZ
  • 26,331
  • 9
  • 49
  • 67

2 Answers2

1

You can implement this by nesting loops over the height and the width of the tree, noting that the output is a * whenever:

  1. it's the first or last row; or
  2. the current x position is less than or equal to the halfway point minus the row number; or
  3. the current x position is greater than or equal to the halfway point plus the row number

For all other cases the output is a space. For example:

function drawTree(height) {
  // compute the width of the tree from the height
  let width = height % 2 ? height + 2 : height + 3;
  // find the halfway point
  let half = (width - 1) / 2;
  for (let i = 0; i < height; i++) {
    let l = '';
    for (let j = 0; j < width; j++) {
      if (i == 0 ||             // first row
        i == height - 1 ||      // last row
        j <= (half - i) ||      // left side
        j >= (half + i)         // right side
      ) {
        l += '*';
      } 
      else {
        l += ' ';
      }
    }
    console.log(l);
  }
}

drawTree(6);
drawTree(5);
Nick
  • 138,499
  • 22
  • 57
  • 95
1
function drawTree(stars, rowLength) {
    for (let row = 0; row < rowLength; row++) {
        if (row === 0) {
            console.log("*".repeat(stars));
        } else if(row === rowLength - 1) {
            console.log("*".repeat(stars));
            
        } else {
            let spaces = 2 * row - 1;
            if (spaces > stars) {
                spaces = stars;
            }
            let numStarsInRow = "*".repeat((stars - spaces) / 2);
            console.log(numStarsInRow + " ".repeat(spaces) + numStarsInRow);
        }
    }
}

drawTree(9, 5)
jdeyrup
  • 1,114
  • 1
  • 12
  • 13