Reputation: 75
I am trying to write a function to return a reverse right triangle but I am having trouble figuring out where I am going wrong.
function triangle(num) {
let star = ""
for (let i = num; i >= 1; i--) {
for (let j = num; j >= 1; j--) {
star += "*" + "\n"
}
}
return star
}
console.log(triangle(6));
My problem is I am having trouble getting the whole function to return a string of * in the form of a reverse triangle. I believe I have concocted the '\n' in the wrong place as well but I am not sure where to change it to.
I am receiving back this:
console.log(triangle(6));
************************************
I am supposed to receive back this:
console.log(triangle(6));
"******\n*****\n****\n***\n**\n*"
I am supposed to concatenate \n to the string output.
-THIS IS WHERE I AM HAVING THE PROBLEM-
Upvotes: 0
Views: 186
Reputation: 135207
for
statements are used to loop in imperative style, whereas functional style uses recursion. Recursion is a functional heritage and so using it with functional style yields the best results. This means avoiding things like variable reassignment and other side effects.
const line = (n = 0) =>
n === 0
? "\n"
: "*" + line(n - 1)
const triangle = (n = 0) =>
n === 0
? ""
: line(n) + triangle(n - 1)
console.log(triangle(6))
******
*****
****
***
**
*
Upvotes: 0
Reputation: 993
I think this is what you want:
function triangle(num) {
let star = ""
for (let i = num; i >= 1; i--) {
for(let j = i; j >= 1; j--) {
star += "*"
}
if(i !== 1) {
star += "\\n"
}
}
return star
}
console.log(triangle(6));
See example here: https://codepen.io/bj-rn-nyborg/pen/gOwOdxR
I moved the +"\n"
to the outer loop, and also initialized let j = i
instead num
Upvotes: 2