Simple Javascript Christmas Tree - javascript

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

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

Related

javascript pyramid within array

I need my output to look like this:
The best I could achieve was that:
Here is my code:
let pyramidComplete = (rows) => {
let array = [];
let str = '';
for (let i = 1; i <= rows; i++) {
//Add the white space to the left
for (let k = 1; k <= (rows - i); k++) {
str += ' ';
}
//Add the '*' for each row
for (let j = 0; j != (2 * i - 1); j++) {
str += "#".repeat(2 * i - 1);
}
//Add the white space to the right
for (let k = i + 1; k <= rows; k++) {
str += ' ';
}
//Print the pyramid pattern for each row
array.push(str)
str = '';
}
}
pyramidComplete(5);
I thought of assembling a line per loop and then, pushing it into an array but, I can't get the desired result.
The logic is fairly direct: for each row, the number of whitespaces is n - i - 1 where i is the row number. The number of # per row is i + 1. You can produce these substrings using String#repeat. Concatenate the two chunks together per line and use the index argument to Array#map's callback to produce each row.
const pyramid = n => Array(n).fill().map((_, i) =>
" ".repeat(n - i - 1) + "#".repeat(i + 1)
);
console.log(pyramid(5));
If the functions used here are incomprehensible, this can be simplified to use rudimentary language features as follows. It's similar to your approach, but the counts for each character per row are different, I iterate from 0 < n rather than 1 <= n and str should be scoped to the outer loop block.
function pyramid (n) {
var result = [];
for (var i = 0; i < n; i++) {
var line = "";
for (var j = 0; j < n - i - 1; j++) {
line += " ";
}
for (var j = 0; j < i + 1; j++) {
line += "#";
}
result.push(line);
}
return result;
}
console.log(pyramid(5));
If you need a true pyramid (which your current output seems to be shooting for, contrary to the expected output):
const pyramid = n => Array(n).fill().map((_, i) => {
const size = i * 2 + 1;
const pad = n - size / 2;
return " ".repeat(pad) + "#".repeat(size) + " ".repeat(pad);
});
console.log(pyramid(5));
I think you want to do this:
let doc, htm, bod, nav, M, I, mobile, S, Q, CharPyr; // for use on other loads
addEventListener('load', ()=>{
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
var w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
var w = within || doc;
return w.querySelectorAll(selector);
}
CharPyr = function(char = '#', className = 'pyr'){
this.char = char; this.className = className;
this.build = (height = 9)=>{
const p = M('div');
p.className = this.className;
for(let i=0,c=this.char,x=c,d; i<height; i++){
d = M('div'); d.textContent = x; p.appendChild(d); x += c;
}
return p;
}
}
// magic happens here
const out1 = I('out1'), out2 = I('out2'), out3 = I('out3'), pyr = new CharPyr;
out1.appendChild(pyr.build(5)); out2.appendChild(pyr.build(7)); out3.appendChild(pyr.build());
}); // end load
*{
box-sizing:border-box;
}
.out{
margin-bottom:7px;
}
.pyr>div{
color:#070; text-align:center;
}
<div class='out' id='out1'></div>
<div class='out' id='out2'></div>
<div class='out' id='out3'></div>

Christmas tree in Javascript using stars

I have this loop problem, I really don't understand why my code doesn't work, I've even draw this on paper and for my logic it looks good but it's not working, please help me.
function drawTree(h) {
for(var i=0; i<=h; i++){
var star = '';
for(var k=0; k<=1; k++){
star += " ";
};
for(var j=0; j<=i; j++) {
star += "*";
};
};
console.log(star);
};
drawTree(5);
See comments in the code for changes.
function drawTree(h) {
for(var i=0; i<=h; i++){
var star = '';
//Changed to start high then decrease
for(var k = 1; k <= h - i; k++){
//shortened to one space
star += " ";
};
for(var j=0; j<=i; j++) {
//Added space so there is an odd number
//of symbols and the star above fits
//the space
star += " *";
};
//Moved into the loop
console.log(star);
};
};
drawTree(5);
Note that the code can be substantially shortened using String.prototype.repeat:
function drawTree(h) {
for (var i = 0; i <= h; i++){
console.log(" ".repeat(h - i) + " *".repeat(i + 1));
};
};
drawTree(5);
Also note that your example produces a base line with six stars for a call of drawTree(5). I am unsure whether that is intended. The code above reproduces said behavior, editing it to show a line less should not be too hard.
function drawTree(h) {
for (var i = 0; i < h; i++) {
var star = '';
var space = (h - i);
if (i == 0) {
star += ' '.repeat(space + 1) + '\n';
}
star += ' '.repeat(space + 1);
var zero = 2 * i + 1;
star += '*'.repeat(zero);
console.log(star);
}
}
drawTree(5);
You’re re-setting it each line, but printing it only at the end.
Move console.log(star); to the end of the first loop.
Just for fun:
const tree = ({height: h = 5, stumpHeight: sh = 2, branchChar: bc = '*', emptyChar: ec = ' ', stumpChar: sc = '#'} = {}) => [
... Array .from ({length: h}, (_, n) => ec .repeat (h - n - 1) + bc.repeat (2 * n + 1) + ec .repeat (h - n - 1)),
... Array .from ({length: sh}, () => ec .repeat (h - 1) + sc + ec .repeat (h - 1)),
] .join ('\n')
console .log (tree ())
console .log (tree ({height: 6, emptyChar: '_'}))
console .log (tree ({height: 12, stumpHeight: 3, stumpChar: '#'}))
console .log (tree ({branchChar: '#'}))
.as-console-wrapper {max-height: 100% !important; top: 0}
Because, you know, that's how all those JS 101 instructors expect it to be coded.
function drawTree(n) {
let tag = "#";
for (let i = 0, j = "#"; i < n; i++) {
console.log(tag);
tag = tag + j;
}
}
drawTree(10);
You have to place the console.log statement inside first for loop. That should give a half tree.
If you want correct tree, then pre-pend spaces before star.
Calculate the center of the number of rows and add spaces before it.
Hope this not an assignment problem.
function drawTree(h) {
for(var i=0; i<=h; i++){
var star = '';
for(var k=0; k<=1; k++){
star += " ";
};
for(var j=0; j<=i; j++) {
star += "*";
};
console.log(star);
};
};
drawTree(5);

How to print a half pyramid in javascript

The code works but I don't want the inner for loop to take me to the new line.
for (i = 0; i < 5; i++) {
for (j = 1; j <= i; j++) {
console.log('*');
}
console.log();
}
console.log('-----------------');
console.log will automatically break the line. Concatenate to a string instead of a log. Log at the end.
let str = '';
for(i = 0; i <= 5 ; i++) {
for(j = 1; j <= i; j++) {
str += '*';
}
str += '\n';
}
console.log(str);
You can do this way, with the help of a string variable:
for (i = 0; i < 5; i++) {
var str = '';
for (j = 1; j <= i; j++) {
str+='*';
}
console.log(str);
}
console.log('-----------------');
If you want to print at the page, use like below
for (i = 0; i < 5; i++) {
let j=0;
do{document.write("*");j++;}while(j < i)
document.write("<br/>")
}
You need to break the line with the console.log you can also controle the space between * with output+='*' + " ";
function pyramid() {
var total = 5;
var output="";
for (var i = 1; i <= total; i++) {
for (var j = 1; j <= i; j++) {
output+='*' + " ";
}
console.log(output);
output="";
}
}
pyramid()
You can get rid of second for loop as follows:
var str = '';
for (i = 1; i <= 5; i++) {
str +=Array(i).join("*");
str +='\n';
}
console.log(str);
let string = "";
for (let i = 0; i < 5; i++){
string += '*';
console.log(string);
}
Output:
*
**
***
****
*****
A simple way to solve this "exercise" in JavaScript:
let width = ""
while(width.length < 6) console.log(width += `#` );
Basically, we create a string (width) and increment its value using the while loop till we hit a restriction.
I found the more typical method "bulky"(?)...plus there's the issue of not getting the exact picture of a half pyramid.
let i,j
for (i= 0; i < 6; i++){
for (j = 0; j<=i; j++){
console.log("#")
}
console.log("\n")
}
function pyramid(n){
let result = "";
for(let i=0; i<=n; i++){
result += "*".repeat(i);
result += "\n"
}
return result;
}
console.log(pyramid(5));
//OutPut
*
**
***
****
*****
As we need n number of pyramid structure with '' / '#' / any symbol. by using above code we can achieve. Here you can see we just created a function called pyramid with one parameter 'n'. and inside function we declare a variable 'result'. So inside for loop the length of 'i' is "<=n" and also you can use "repeat() method to print '' 'i' times. So if you call that function like console.log(pyramid(5)); You can able to see your Answer as expected..
shortest code:
console.log('*\n**\n***\n****\n*****');

Pyramide of Stars Javascript

How could I create Pyramide of Stars that increase every row by 2 like that:
*
* * *
* * * * *
* * * * * * *
My currently code:
for (var x = 0; x < 5; x++) {
for (var y = 0; y <= x; y = y + 1) {
document.write(" * ");
}
document.write("<br>");
}
It's possible just to increment in your loop by 2.
for(var i = 1; i < 20; i += 2) {
console.log( Array(i).fill('*').join(' ') );
}
Otherwise just multiply inside your loop
for(var i = 0; i < 10; i++) {
console.log( Array(i*2 + 1).fill('*').join(' ') );
}
You may also need to polyfill Array.fill depending on your target.
Other answers recreate the entire row each time. This solution just extends the row each time to have another star.
function pyramid(n) {
let result = '', str = '', add = '*';
for (var i = 0; i < n; i++) {
str += add;
add = ' *';
if (!(i % 2)) result += str + '\n';
}
return result;
}
console.log(pyramid(5));
You can do like this.
function generate() {
var totalNumberofRows = 5;
var output="";
for (var i = 1; i <= totalNumberofRows; i++) {
for (var j = 1; j <= i; j++) {
if(j==1)
output+="*";
else
output+=" "+ "*" + " "+ "*";
}
console.log(output);
output="";
}
}
generate()
Hope so this is also beneficial for you....
$(document).ready(function () {
var NumberofRows = 5,arr;
for (var i = 1; i <= NumberofRows; i++) {
pyramid = [];
for (var j = 1; j <= i; j++) {
pyramid.push('*');
}
console.log(pyramid.join(" ") + "\n");
}
});
``

Exercise with a loop in javascript

I need for an university exercise to display onscreen with a document.write the tree below using a kind of loop:
I used at the beginning a for loop but i printed only the first row... someone can help me?
This is what I tried:
var numbers = [0, 1, 2, 3, 4]
for (var i = 0; i <= numbers.length; i++) {
if (numbers [i] == 0) {
document.write(" * </br>");
}
if (numbers [i] == 1) {
document.write(" *** </br>");
}
if (numbers [i] == 2) {
document.write(" ****** </br>");
}
if (numbers [i] == 3) {
document.write(" ******* </br>"); }
if (numbers [i] == 4) {
document.write("********* </br>");
}
return
}
Thank You!
I'm going to give you a "golfed-ish" (goldfish? should this be a thing?) version of the code. In other words, the smallest, most obscure code I can think of to accomplish the task. You should not use this, because your teacher will undoubtedly ask you what it means and you won't know, but I'm bored XD
var size = 5;
document.write("<center>"+Array.apply(0,new Array(size)).map(function(_,i) {return new Array((i+1)*2).join(" * ");}).join("<br>")+"</center>");
Demo
As I said, don't use this :p
Here is my code for you ...
<html>
<head>
<script type="text/javascript" language="javascript">
document.write("<center>"); //write a center tag to make sure the pyramid displays correctly(try it without this step to see what happens)
for(var i = 0; i <= 10; i++) //a loop, this counts from 0 to 10 (how many rows of stars)
{
for(var x = 0; x <= i; x++)// a loop, counting from 0 to whatever value i is currently on
{
document.write("*");//write a * character
}
document.write("<br/>"); //write a br tag, meaning new line, after every star in the row has been created
}
document.write("</center>"); //close the center tag, opened at the beginning
</script>
</head>
<body>
</body>
</html>
Adds spaces and fully extendable
function pyramid(lines, char) {
var start = 2,html = '<pre>';
for (var i=lines; i--;) {
html += new Array(Math.floor(i+1)).join(' ') + new Array((start=start+2)-2).join(char) + '<br />';
}
return html + '</pre>';
}
document.write( pyramid(5, '*') );
FIDDLE
function pyramidStar(n) {
var str = "";
for(var i=1; i<=n; i++) {
for(var j=1; j<=n-i; j++) {
str += " ";
}
for(var k=n-i+1; k<n+i; k++) {
str += "* ";
}
for(var m=n+i; m<=2*n-1; m++) {
str += " ";
}
str += "\n";
}
return str;
}
document.getElementById("result").innerHTML = pyramidStar(9);
<pre id="result"></pre>
Another way of printing pyramid of stars.
<pre><script>
for (var i = 0; i < 5; i++) {
for (var c = 0; c < 9; c++) {
if (Math.abs(4 - c) <= i)
document.write("*");
else
document.write(" ");
}
document.write("<br />");
}
</script></pre>
It is a simple version with document.write(). The only complicated thing is Math.abs which gives the distance from the middle.
PS: watch out for magic numbers
function star(n) {
for (var i = 1; i <= n; i++) {
for (var j = i; j < n; j++) {
document.write("-");
}
for (var k = 1; k <= (2 * i) - 1; k++) {
document.write("*");
}
document.write("<br/>");
}
}
//function calling
star(9);

Categories

Resources