Add test case to Binomial Coefficient Algorithm (#3179)

Co-authored-by: Yang Libin <contact@yanglibin.info>
This commit is contained in:
Ankush Banik 2022-07-05 15:07:11 +05:30 committed by GitHub
parent f273b30998
commit 3fb9a606a3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 38 additions and 27 deletions

View File

@ -11,36 +11,29 @@ package com.thealgorithms.maths;
* */
public class BinomialCoefficient {
/**
/**
* This method returns the number of ways in which k objects can be chosen from n objects
*
* @param total_objects Total number of objects
* @param no_of_objects Number of objects to be chosen from total_objects
* @param totalObjects Total number of objects
* @param numberOfObjects Number of objects to be chosen from total_objects
* @return number of ways in which no_of_objects objects can be chosen from total_objects objects
*/
static int binomialCoefficient(int total_objects, int no_of_objects) {
//Base Case
if(no_of_objects > total_objects) {
return 0;
}
//Base Case
if(no_of_objects == 0 || no_of_objects == total_objects) {
return 1;
}
//Recursive Call
return binomialCoefficient(total_objects - 1, no_of_objects - 1)
+ binomialCoefficient(total_objects - 1, no_of_objects);
}
public static void main(String[] args) {
System.out.println(binomialCoefficient(20,2));
//Output: 190
}
public static int binomialCoefficient(int totalObjects, int numberOfObjects) {
// Base Case
if (numberOfObjects > totalObjects) {
return 0;
}
// Base Case
if (numberOfObjects == 0 || numberOfObjects == totalObjects) {
return 1;
}
// Recursive Call
return binomialCoefficient(totalObjects - 1, numberOfObjects - 1)
+ binomialCoefficient(totalObjects - 1, numberOfObjects);
}
}

View File

@ -0,0 +1,18 @@
package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class BinomialCoefficientTest {
@Test
void testBinomialCoefficient() {
assertEquals(190, BinomialCoefficient.binomialCoefficient(20, 2));
assertEquals(792, BinomialCoefficient.binomialCoefficient(12, 5));
assertEquals(84, BinomialCoefficient.binomialCoefficient(9, 3));
assertEquals(1, BinomialCoefficient.binomialCoefficient(17, 17));
}
}