Skip to content

feat: Pascal's Triangle #121

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Apr 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions maths/pascals_triangle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Pascal's Triangle is an array of binomial coefficients. It can be used for unwrapping terms like
* (a + b)^5.
* To construct Pascal's Triangle you add the numbers above the child entry together. Here are the first five rows:
* 1
* 1 1
* 1 2 1
* 1 3 3 1
* 1 4 6 4 1
*
* Time Complexity: quadratic (O(n^2)).
*
* @param n The exponent / The index of the searched row.
* @returns The nth row of Pascal's Triangle
* @see https://en.wikipedia.org/wiki/Pascal's_triangle
*/
export const pascalsTriangle = (n: number): number[] => {
let arr: number[][] = [];
for (let i: number = 0; i < n; i++) {
if (i === 0) {
arr.push([1]);
continue;
}

let lastRow: number[] = arr[i - 1];
let temp: number[] = [];
for (let j: number = 0; j < lastRow.length + 1; j++) {
if (j === 0 || j === lastRow.length) {
temp.push(1);
continue;
}

temp.push(lastRow[j - 1] + lastRow[j]);
}

arr.push(temp);
}

return arr[arr.length - 1];
};
11 changes: 11 additions & 0 deletions maths/test/pascals_triangle.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { pascalsTriangle } from "../pascals_triangle";

describe('pascalsTriangle', () => {
it.each([
[2, [1, 1]],
[4, [1, 3, 3, 1]],
[6, [1, 5, 10, 10, 5, 1]],
])('The %i th row should equal to %i', (n, expectation) => {
expect(pascalsTriangle(n)).toEqual(expectation);
});
});