mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 09:45:04 +08:00
Add test case to Binomial Coefficient Algorithm (#3179)
Co-authored-by: Yang Libin <contact@yanglibin.info>
This commit is contained in:
@ -15,32 +15,25 @@ public class BinomialCoefficient {
|
|||||||
/**
|
/**
|
||||||
* This method returns the number of ways in which k objects can be chosen from n objects
|
* 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 totalObjects Total number of objects
|
||||||
* @param no_of_objects Number of objects to be chosen from total_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
|
* @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) {
|
public static int binomialCoefficient(int totalObjects, int numberOfObjects) {
|
||||||
|
|
||||||
// Base Case
|
// Base Case
|
||||||
if(no_of_objects > total_objects) {
|
if (numberOfObjects > totalObjects) {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Base Case
|
// Base Case
|
||||||
if(no_of_objects == 0 || no_of_objects == total_objects) {
|
if (numberOfObjects == 0 || numberOfObjects == totalObjects) {
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Recursive Call
|
// Recursive Call
|
||||||
return binomialCoefficient(total_objects - 1, no_of_objects - 1)
|
return binomialCoefficient(totalObjects - 1, numberOfObjects - 1)
|
||||||
+ binomialCoefficient(total_objects - 1, no_of_objects);
|
+ binomialCoefficient(totalObjects - 1, numberOfObjects);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
System.out.println(binomialCoefficient(20,2));
|
|
||||||
|
|
||||||
//Output: 190
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -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));
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user