0

I have been trying to solve printing down left side star(*) pattern in Javascript using recursion, i think my logic is correct but my syntax and concept might be wrong

// * * * * *
// * * * *
// * * *
// * *
// *

This is my code solution so far

var triangle = function (row, col) {
    if(row == 0){
        return
    }
    if(col < row){
        console.log("*")
        triangle(row, col + 1)
    }else{
        console.log("\n")
        triangle(row - 1, 0)
    }
}
triangle(4, 0)

output

*
*
*
*


*
*
*


*
*


*

But i want the output to be

* * * * *
* * * *
* * *
* *
*
  • 2
    Evidently, [it is not possible to call console.log() without a newline](https://stackoverflow.com/questions/9627646/chrome-javascript-developer-console-is-it-possible-to-call-console-log-withou). "You'll have to keep a string and concatenate if you want it all in one line..." – showdev Nov 25 '22 at 05:05

2 Answers2

1

console.log() closes the output stream automatically, the "line break" is because it is the next output session. You will see its true form if you use document.write.

var triangle = function (row, col) {
    if(row == 0){
        return
    }
    if(col < row){
        document.write("*")
        triangle(row, col + 1)
    }else{
        document.write("<br/>")
        triangle(row - 1, 0)
    }
}
triangle(4, 0)

But if you insist to use console.log(), some modification must be made:

var triangle = function (row, col, stream = '') {
    if(row == 0){
        return
    }
    if(col < row){
        stream += '*'
        triangle(row, col + 1, stream)
    }else{
        console.log(stream)
        stream = ''
        triangle(row - 1, 0, stream)
    }
}
triangle(4, 0)
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
  • Thanks man..... I think I would go with the second solution, the first solution return an error when run in VS code "ReferenceError: document is not defined" since i am not running it on HTML environment – Danities Ichaba Nov 28 '22 at 04:08
0

check this solution

 function triangle(row){
        var print="";
        if(row==0){
            return;
        }
        for(var i=0;i<row;i++){
            print+="* "
        }
        console.log(print);
        triangle(row-1);
        
    }
    triangle(5);
Maulik
  • 39
  • 2
  • Thanks man....I appreciate, this is cleaner but i think running it on for loop would increase it complexity(i might be wrong though) – Danities Ichaba Nov 28 '22 at 04:10