8000 Added PascalsTriangle algorithm using Recursion · AllAlgorithms/javascript@dc2176d · GitHub
[go: up one dir, main page]

Skip to content
8000

Commit dc2176d

Browse files
whoisnpabranhe
authored andcommitted
Added PascalsTriangle algorithm using Recursion
1 parent ecc36fb commit dc2176d

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

algorithms/math/pascalsTriangle.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
function pascalTriangleRecursive(lineNumber) {
2+
if (lineNumber === 0) {
3+
return [1];
4+
}
5+
6+
const currentLineSize = lineNumber + 1;
7+
const previousLineSize = currentLineSize - 1;
8+
9+
const currentLine = [];
10+
11+
const previousLine = pascalTriangleRecursive(lineNumber - 1);
12+
13+
for (let numIndex = 0; numIndex < currentLineSize; numIndex += 1) {
14+
const leftCoefficient = numIndex - 1 >= 0 ? previousLine[numIndex - 1] : 0;
15+
const rightCoefficient =
16+
numIndex < previousLineSize ? previousLine[numIndex] : 0;
17+
18+
currentLine[numIndex] = leftCoefficient + rightCoefficient;
19+
}
20+
21+
return currentLine;
22+
}
23+
console.log(pascalTriangleRecursive(40));

0 commit comments

Comments
 (0)
0