Skip to content

Commit

Permalink
feat: added binomial coefficient function and the corresponding test #10
Browse files Browse the repository at this point in the history
 (#141)
  • Loading branch information
Tcheumen authored Jul 3, 2023
1 parent 0fa510b commit 24c861f
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
24 changes: 24 additions & 0 deletions maths/binomial_coefficient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Factorial } from "./factorial";
/**
* @function BinomialCoefficient
* @description Calculate the binomial coefficient (n choose k) of two input numbers.
* @param {number} n - the total number of items
* @param {number} k - the number of items to be chosen
* @return {number} - Binomial coefficient (n choose k)
* @see https://en.wikipedia.org/wiki/Binomial_coefficient
* @example BinomialCoefficient(5, 2) = 10
* @example BinomialCoefficient(10, 3) = 120
* @example BinomialCoefficient(6, 0) = 1
*/

export const BinomialCoefficient = (n: number, k: number): number => {
// Check if k is larger than n or negative
if (k > n || k < 0) {
return 0;
}

// Calculate the binomial coefficient using the implemented factorial
const numerator = Factorial(n);
const denominator = Factorial(k) * Factorial(n - k);
return numerator / denominator;
};
34 changes: 34 additions & 0 deletions maths/test/binomial_coefficient.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { BinomialCoefficient } from '../binomial_coefficient';

describe('BinomialCoefficient', () => {
it('should calculate the correct binomial coefficient', () => {
// Test cases with expected results
const testCases: [number, number, number][] = [
[5, 2, 10],
[10, 3, 120],
[6, 0, 1],
[4, 4, 1],
[7, 5, 21],
[10, 10, 1],
];

// Iterate through each test case and verify the result
testCases.forEach(([n, k, expected]) => {
const result = BinomialCoefficient(n, k);
expect(result).toEqual(expected);
});
});

it('should return 0 if k is larger than n or negative', () => {
const invalidCases: [number, number][] = [
[5, 6], // k is larger than n
[10, -3], // k is negative
[5, 10], // k is larger than n
];

invalidCases.forEach(([n, k]) => {
const result = BinomialCoefficient(n, k);
expect(result).toEqual(0);
});
});
});

0 comments on commit 24c861f

Please sign in to comment.