John Smith
John Smith

Reputation: 107

Simple Javascript Christmas Tree

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>");
}

Upvotes: 1

Views: 23646

Answers (8)

enrico
enrico

Reputation: 71

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);

Upvotes: 2

Dovilė Sem
Dovilė Sem

Reputation: 11

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

Upvotes: 0

Maven
Maven

Reputation: 91

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));

Upvotes: 0

exside
exside

Reputation: 3894

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 =)...

Upvotes: 2

Joris Schellekens
Joris Schellekens

Reputation: 9032

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**     
   *****⛣**⛣  
  *****⌾****⏣ 
 **◍*◍********
      ****
      ****

Upvotes: 5

Friendly
Friendly

Reputation: 1

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;
}

Upvotes: 0

user6820627
user6820627

Reputation:

<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.

Upvotes: 5

Rax Weber
Rax Weber

Reputation: 3780

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

Upvotes: 2

Related Questions