Skip to content

Commit e85ea1b

Browse files
zFlxwappgurueu
andauthored
feat: Pascal's Triangle (TheAlgorithms#121)
* feat(data-struct): binary search tree * fix: improvements part 1 * fix: improvements part 2 * Fix failing tests * feat: pascals triangle --------- Co-authored-by: Lars Müller <[email protected]>
1 parent 05d876d commit e85ea1b

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

maths/pascals_triangle.ts

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Pascal's Triangle is an array of binomial coefficients. It can be used for unwrapping terms like
3+
* (a + b)^5.
4+
* To construct Pascal's Triangle you add the numbers above the child entry together. Here are the first five rows:
5+
* 1
6+
* 1 1
7+
* 1 2 1
8+
* 1 3 3 1
9+
* 1 4 6 4 1
10+
*
11+
* Time Complexity: quadratic (O(n^2)).
12+
*
13+
* @param n The exponent / The index of the searched row.
14+
* @returns The nth row of Pascal's Triangle
15+
* @see https://en.wikipedia.org/wiki/Pascal's_triangle
16+
*/
17+
export const pascalsTriangle = (n: number): number[] => {
18+
let arr: number[][] = [];
19+
for (let i: number = 0; i < n; i++) {
20+
if (i === 0) {
21+
arr.push([1]);
22+
continue;
23+
}
24+
25+
let lastRow: number[] = arr[i - 1];
26+
let temp: number[] = [];
27+
for (let j: number = 0; j < lastRow.length + 1; j++) {
28+
if (j === 0 || j === lastRow.length) {
29+
temp.push(1);
30+
continue;
31+
}
32+
33+
temp.push(lastRow[j - 1] + lastRow[j]);
34+
}
35+
36+
arr.push(temp);
37+
}
38+
39+
return arr[arr.length - 1];
40+
};

maths/test/pascals_triangle.test.ts

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { pascalsTriangle } from "../pascals_triangle";
2+
3+
describe('pascalsTriangle', () => {
4+
it.each([
5+
[2, [1, 1]],
6+
[4, [1, 3, 3, 1]],
7+
[6, [1, 5, 10, 10, 5, 1]],
8+
])('The %i th row should equal to %i', (n, expectation) => {
9+
expect(pascalsTriangle(n)).toEqual(expectation);
10+
});
11+
});

0 commit comments

Comments
 (0)