From 24c861fb8550f95c37f19c1d831150aaa6e75c39 Mon Sep 17 00:00:00 2001 From: Tcheumen <107006692+Tcheumen@users.noreply.github.com> Date: Mon, 3 Jul 2023 19:01:28 +0200 Subject: [PATCH] feat: added binomial coefficient function and the corresponding test #10 (#141) --- maths/binomial_coefficient.ts | 24 +++++++++++++++++ maths/test/binomial_coefficient.test.ts | 34 +++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 maths/binomial_coefficient.ts create mode 100644 maths/test/binomial_coefficient.test.ts diff --git a/maths/binomial_coefficient.ts b/maths/binomial_coefficient.ts new file mode 100644 index 00000000..cc522c3b --- /dev/null +++ b/maths/binomial_coefficient.ts @@ -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; +}; diff --git a/maths/test/binomial_coefficient.test.ts b/maths/test/binomial_coefficient.test.ts new file mode 100644 index 00000000..ca677264 --- /dev/null +++ b/maths/test/binomial_coefficient.test.ts @@ -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); + }); + }); +});