最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Simple Javascript Christmas Tree - Stack Overflow

programmeradmin1浏览0评论

I created a half of the Christmas Tree but here I got blocked. Some one please help me to understand how to do the left side too.

for (var i = 0; i < 8; i++) {
  for (var j = 0; j <= i; j++) {
     document.write("^"); 
  }
  document.write("<br>");
}

I created a half of the Christmas Tree but here I got blocked. Some one please help me to understand how to do the left side too.

for (var i = 0; i < 8; i++) {
  for (var j = 0; j <= i; j++) {
     document.write("^"); 
  }
  document.write("<br>");
}

Share Improve this question asked Oct 13, 2016 at 8:33 John SmithJohn Smith 1071 gold badge1 silver badge9 bronze badges 8
  • Use the pre element and add spaces to the left side. – evolutionxbox Commented Oct 13, 2016 at 8:35
  • I don't know how to do that. I'm not an advance guy. Can u show me please? – John Smith Commented Oct 13, 2016 at 8:37
  • 1 Advanced? I think you need to read some JavaScript tutorials. – evolutionxbox Commented Oct 13, 2016 at 8:38
  • the christmas trees that I found were too complicated with no explination and that is why I wanted to understand how to create a simple one. – John Smith Commented Oct 13, 2016 at 8:40
  • Don't use document.write, and you can use css to align your text centrally (hint: text-align: center). – evolutionxbox Commented Oct 13, 2016 at 8:43
 |  Show 3 more comments

8 Answers 8

Reset to default 5

<pre>
<script>
    //Reads number of rows to be printed
    var n = 8;
 
    for(i=1; i<=n; i++)
    { 
        //Prints trailing spaces
        for(j=i; j<n; j++)
        {
            document.write(" ");
        }
 
        //Prints the pyramid pattern
        for(j=1; j<=(2*i-1); j++)
        {
            document.write("*");
        }
 
        document.write("<br>");

        }
</script>
</pre>

Source: http://codeforwin.org/2015/07/equilateral-triangle-star-pattern-program-in-c.html

C to JavaScript by me.

I wrote the following code for this problem.
I also added a nice extra, christmas-tree ornaments :-)

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    private static Random RND = new Random(System.currentTimeMillis()); // useful for placing balls
    private static char[] BALLS = {'o','⌾','⛣','⏣','◍'}; // symbols being used as balls

    public static void main (String[] args) throws java.lang.Exception
    {
        int w = 27; // width of the tree
        int b = 10; // number of balls in the tree
        String tree = ""; // this will end up containing the tree

        // build tree
        w = ( w % 2 == 1 ) ? w : 13; // check whether width is odd
        for(int i=1;i<=w;i+=2){
            int s = (w - i) / 2;
            tree += repeat(' ', s) + repeat('*', i) + repeat(' ', s) + "\n";
        }

        // randomly replace some parts by balls
        int i=0;
        while(i < b){
            int j = RND.nextInt(tree.length());
            if(tree.charAt(j) == '*'){
                tree = tree.substring(0, j) + BALLS[RND.nextInt(BALLS.length)] + tree.substring(j+1);
                i++;
            }
        }

        // build trunk
        tree += repeat(' ', (w - 4) / 2) + repeat('*', 4) + "\n" + repeat(' ', (w - 4) / 2) + repeat('*', 4);

        // output
        System.out.println(tree);
    }

    // this function builds a String by repeating a given character a couple of times
    private static String repeat(char c, int l){
        String s = "";
        for(int i=0;i<l;i++)
            s += c;
        return s;
    }
}

The output should look something like this:

       ⏣        
      ***       
     *o***    
    **⌾*o**     
   *****⛣**⛣  
  *****⌾****⏣ 
 **◍*◍********
      ****
      ****

The keyword is think.

var x = 8;
for (let i = 0; i < x; i++) {
   for (let j=x-1; j>i; j--) {
      document.write("&nbsp&nbsp"); 
   }
   for (let k=0; k<=(i*2); k++) {
      document.write("^"); 
   }
   document.write("<br>");
}
for (let i=0; i<2; i++) {
    for (let j=0; j<(x*2)-3; j++) {
        document.write("&nbsp");
    }
    document.write("^<br>");
}

Constraints: Only looks good starting from x = 5.

Original code by me

The answers above heavily rely on nested loops, thought I post another approach with "modern" JS (of course still using a single loop with the map function given to Array.from()):

function xmas(height) {
    // add 1 more level for the trunk, e.g. height+1
    return Array.from({length: height+1}, (v, i) => {
        return i === height
            // that's for the trunk of the tree
            ? '*'.padStart(Math.round((2 * i)/2), ' ')
            // the actual tree "levels"
            : '*'.repeat(2 * i + 1).padStart(2 * i + height-i, ' ');
    }).join('\n');
}

document.write(`<pre>${xmas(10)}</pre>`);

maybe the attempt to make it work with .padStart() is not optimal because the math gets a bit ugly, but anyways, just for fun =)...

Here's a solution with a simple for loop without any nested loop.

let row = ""
let l = 9

for (let i = 0; i < l; i++) {
  row += " ".repeat(l - i) + "*" + "*".repeat(i * 2) + `\n`;
}
console.log(row);

Simple christmas tree function:

function christmasTree(x) {
    if(x < 3) {
        return "";
    }
    let tree = "";
    for(let i = 1; i <= x; i++) {
        for(let j = 1; j <= x + x - 1; j++) {
            if(j <= x - i || j >= x + i) {
                tree += " ";
            } else {
                tree += "*";
            }
        }
        tree += "\n";
    }
    return tree;
}

Incase you are looking for how to do this in a function for javascript or typescript

Use 3 for loops, 1 - Number of rows 2 - Number of spaces 3 - Number of characters

  function christmas(n) {
   let tree = '';
    for (let i = 1; i <= n; i++) {
     for (let j=0; j <= n-i; j++) {
      tree += ' ';
     }
     for (k = 0; k< (i*2)-1; k++) {
      tree += '*';
     }
     tree += '\n';
    }
     return tree;
   }

     console.log(christmas(3));

<pre>
<script>
    //Reads number of rows to be printed
    var n = 8;
 
    for(i=1; i<=n; i++)
    { 
        //Prints trailing spaces
        for(j=i; j<n; j++)
        {
            document.write(" ");
        }
 
        //Prints the pyramid pattern
        for(j=1; j<=(2*i-1); j++)
        {
            document.write("*");
        }
 
        document.write("<br>");

        }
</script>
</pre>

发布评论

评论列表(0)

  1. 暂无评论