File tree Expand file tree Collapse file tree 2 files changed +58
-0
lines changed Expand file tree Collapse file tree 2 files changed +58
-0
lines changed Original file line number Diff line number Diff line change 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+ } ;
Original file line number Diff line number Diff line change 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+ } ) ;
You can’t perform that action at this time.
0 commit comments