Skip to content

Commit 24c861f

Browse files
authored
feat: added binomial coefficient function and the corresponding test #10 (#141)
1 parent 0fa510b commit 24c861f

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

maths/binomial_coefficient.ts

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { Factorial } from "./factorial";
2+
/**
3+
* @function BinomialCoefficient
4+
* @description Calculate the binomial coefficient (n choose k) of two input numbers.
5+
* @param {number} n - the total number of items
6+
* @param {number} k - the number of items to be chosen
7+
* @return {number} - Binomial coefficient (n choose k)
8+
* @see https://en.wikipedia.org/wiki/Binomial_coefficient
9+
* @example BinomialCoefficient(5, 2) = 10
10+
* @example BinomialCoefficient(10, 3) = 120
11+
* @example BinomialCoefficient(6, 0) = 1
12+
*/
13+
14+
export const BinomialCoefficient = (n: number, k: number): number => {
15+
// Check if k is larger than n or negative
16+
if (k > n || k < 0) {
17+
return 0;
18+
}
19+
20+
// Calculate the binomial coefficient using the implemented factorial
21+
const numerator = Factorial(n);
22+
const denominator = Factorial(k) * Factorial(n - k);
23+
return numerator / denominator;
24+
};
+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { BinomialCoefficient } from '../binomial_coefficient';
2+
3+
describe('BinomialCoefficient', () => {
4+
it('should calculate the correct binomial coefficient', () => {
5+
// Test cases with expected results
6+
const testCases: [number, number, number][] = [
7+
[5, 2, 10],
8+
[10, 3, 120],
9+
[6, 0, 1],
10+
[4, 4, 1],
11+
[7, 5, 21],
12+
[10, 10, 1],
13+
];
14+
15+
// Iterate through each test case and verify the result
16+
testCases.forEach(([n, k, expected]) => {
17+
const result = BinomialCoefficient(n, k);
18+
expect(result).toEqual(expected);
19+
});
20+
});
21+
22+
it('should return 0 if k is larger than n or negative', () => {
23+
const invalidCases: [number, number][] = [
24+
[5, 6], // k is larger than n
25+
[10, -3], // k is negative
26+
[5, 10], // k is larger than n
27+
];
28+
29+
invalidCases.forEach(([n, k]) => {
30+
const result = BinomialCoefficient(n, k);
31+
expect(result).toEqual(0);
32+
});
33+
});
34+
});

0 commit comments

Comments
 (0)