Forming an inverted ascii triangle art using JS looping

1.2k Views Asked by At

Without nesting loops, how are you able to form such an ascii art?

####
###
##
#

This is what I currently have:

function invertTriangle (row) {
  var asteric = "*" * row;
  for ( var y=row; y>=row; y--){
      asteric = asteric - "*";
      console.log(asteric);
  }
};

invertTriangle(10);

I will appreciate your help and explanation!

Thank you!

2

There are 2 best solutions below

0
On

Here's a way of doing it with recursion.

Basically, you call the function with the number of chars you'd like printed on the first line. It then constructs a string with this many characters in it. It then decrements the number of chars wanted and, if this number is greater than 0, calls itself again and adds the new result to the current result. This continues until we get to a line that requires zero characters. At this point, the function no longer calls itself and the fully constructed string is returned to the original caller.

Code:

<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}

window.addEventListener('load', onDocLoaded, false);

function onDocLoaded()
{
    byId('triTgt').innerText = makeTriString(40);
}

function makeTriString(nStars)
{
    var str = '';
    for (var i=0; i<nStars; i++)
        str += "*";
    str += "\n";
    nStars--;
    if (nStars > 0)
        str += makeTriString(nStars);
    return str;
}
</script>
<style>
</style>
</head>
<body>
    <div id='triTgt'></div>
</body>
</html>
1
On

Try:

var string = "";

for (var i = 0, j = 4, k = 4; i < 10; i++) {
    string += "*";
    if (--j === 0) {
        j = --k;
        string += "\n";
    }
}

alert(string);

Hope that helps.