How to draw such a triangle in JavaScript?
*
***
*****
*******
*********
***********
*************
It would be great if you could explain how it works.
So far I have this code:
let lines = 7;
let str = ' ';
for (let i = 0; i < lines; i++) {
str += '*';
console.log(str);
}
First specify the dimensions of the picture, and then specify the coordinates of the vertices of the spruce trees.
Spruce forest:
* *
*** * *** * *
***** *** ***** *** * ***
******* ***** ******* ***** *** * *****
********* **************** ******* ***** * *** *******
************************************* ******* *** ***** *********
*************************************** ********* ***** ******* ***********
************************************************** ******* ********************
********************************************************************************
function spruceForest(width, height) {
let forest = {
plot: [],
addSpruce: function(x, y) {
for (let i = 0; i < height - y; i++)
for (let j = -i; j <= i; j++)
if (x + j >= 0 && x + j < width)
this.plot[y + i][x + j] = 1;
return this;
},
output: function() {
for (let i = 0; i < height; i++) {
let row = this.plot[i];
let line = '';
for (let j = 0; j < width; j++)
line += row[j] == 1 ? '*' : ' ';
console.log(line);
}
}
}; // populate an empty plot
for (let i = 0; i < height; i++) {
forest.plot[i] = [];
for (let j = 0; j < width; j++)
forest.plot[i][j] = '';
}
return forest;
}
spruceForest(80, 9) // draw a spruce forest in ASCII-art style
.addSpruce(6, 0).addSpruce(15, 1).addSpruce(23, 0)
.addSpruce(33, 1).addSpruce(44, 2).addSpruce(55, 4)
.addSpruce(64, 3).addSpruce(74, 1).output();
Inspired by this answer: Draw an ASCII spruce forest in Java