简体   繁体   中英

Tree exercise with a loop in javascript

I want to create a tree with *. I will give a number every time in order to specify the tree's height. It should look something like this if I give number 4 as height for example:

    *
   ***
  *****
 *******

I would like the tree to appear using console.log

I have done that:

 var size = 4; document.write( "<center>" + Array.apply(0, new Array(size)).map(function(_, i) { return new Array((i + 1) * 2).join(" * "); }).join("<br>") + "</center>" );

but it doesn't work if I use console.log

You just need to count the spaces on the left per floor. The deepest one starts at j=0 . The floor above at j=1 . And so forth.

Given a height h ,

  • floor h-1->j=0
  • floor h-2->j=1
  • floor 0->j=h-1

Notice that if you start at floor 0 , you get j=h-1 , and remove a space at every subsequent floor.

You can thus trivially write

 const h = 4; console.log(Array(h).fill(0).map((_,i)=>{ return ' '.repeat(h-1-i)+'*'.repeat(i*2+1) }).join('\n'))

To clearify my comment. You won't be able to show html in the console. So you need to forget about tags. As when you are printing the tree you should know how big (height) it's going to be. So you know how many spaces will preceed your star.

Number of spaces are given by the height in total - the current "level" from top to bottom - 1

and the number of stars is given by 2 times of the current "level" plus 1

let spaces = " ".repeat(height-i-1);
let stars = "*".repeat(i*2+1);

So just use a loop to go through all the levels of the tree from top to bottom and concatinating the spaces and stars

Here's an example on how that works (example also prints out to a textarea for preview purposes as well as in the console)

https://codepen.io/relief_melone/pen/zYYRZmj

I created one like this.

function drawTree(height) {
        for ( let i = 0; i < height ; i++ ) {
            let star = '*';
            let space = ' ';

            for ( let j = 1; j <= i; j++ ) {
                star = star + '**';            
            }

            let gap = space.repeat(height-i-1);
            star = gap + star;
            console.log(star);
        }
    }

    let number = prompt('Give number for tree height');

    drawTree(number);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM