Reputation: 749
I want to try to make isosceles triangle but I have trouble making it this is so far I got:
function pyramid(N) {
let result = "";
for (let i = 1; i <= N; i++) {
for (let j = 1; j <= N; j++) {
if (i >= j) {
result += i + " ";
} else {
result += " ";
}
}
result += '\n';
}
return result
}
console.log(pyramid(5));
my output:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
the output I want is:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
is it necessary to loop again to make it?
Upvotes: 1
Views: 1831
Reputation: 389
The below code will give you the desired output.
function pyramid(N){
let result = "";
for(let i = 1 ; i <= N ; i++) {
for(j = N ; j > i ; j--) {
result += " ";
}
for(j = 1 ; j<= i ; j++) {
result += i + " ";
}
result += "\n";
}
return result;
}
console.log(pyramid(5));
Upvotes: 1
Reputation: 168913
You could replace the creation of const line
with your original code, this is just a little more succinct.
function pyramid(N) {
let result = "";
// Figure out the length of the last line.
const lastLineLength = 2 * N - 1;
for (let i = 1; i <= N; i++) {
// Create an array of length i, fill it with the digit i,
// join by spaces to create the string.
const line = new Array(i).fill(i).join(" ");
// Figure out how much padding to add to this line to center-align the triangle.
const leftPaddingLength = Math.floor((lastLineLength - line.length) / 2);
// Create the padded line.
const paddedLine = line.padStart(line.length + leftPaddingLength);
result += paddedLine + "\n";
}
return result;
}
console.log(pyramid(5));
Upvotes: 0