I want to print numbers in this format.
1
121
12321
1234321
123454321
I wrote a function that prints some numbers but it is not the same as the output. I think the bug is maybe inside one of the for loops. Here's my code:
var numRows = 5, triangle, start, stop; function pascalRecursive(n, a) { if (n < 2) return a; var prevRow = a[a.length-1]; var curRow = [1]; for (var i = 1; i < prevRow.length; i++) { curRow[i] = prevRow[i] + prevRow[i]; } curRow.push(1); a.push(curRow); return pascalRecursive(n-1, a); } var triangle = pascalRecursive(numRows, [[1]]); for(var i = 0; i < triangle.length; i++) console.log(triangle[i]+"\\n");
you could you a map function to increase all the numbers of the previous line by 1 then just stick a 1 to the front and end.
function pascalRecursive(n, a) {
if (n < 2) return a;
var prevRow = a[a.length - 1];
var prevRowIncreased = prevRow.map(x => x + 1);
a.push([1,...prevRowIncreased,1]);
return pascalRecursive(n - 1, a);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.