We can get the combination of a number by creating a function. A combination is used to find the number of possible arrangements of objects without regarding the order in which they are selected.
We will use the mathematical formula below where we use some factorials n!
, r!
, and (n-r)!
. Hence, we will create a function that returns the factorial.
From the illustration above, we can see that:
n
C
r
: Represents the number of combinations.n
: Represents the total number of objects.r
: Represents the number of chosen objects.The syntax for finding the factorial of a number is as follows:
for(counter; counter <= number; counter++) {result = result * counter;}
The parameters in the loop are as follows:
counter
: Represents a counter. It will be used for looping.number
: Represents the number whose factorial we want to find.Let's look at a code example below:
class HelloWorld {// create the factorial functionpublic static int factorial(int num){int result = 1, counter;// create for loopfor(counter=1; counter<=num; counter++){result = result*counter;}return result;}public static void main( String args[] ) {// create some numbers of objects we want to get the combinationint n1 = 10;int n2 = 4;// create number of the objects are taken at a timeint r1 = 3;int r2 = 2;// get the combination based on the mathematical formulaSystem.out.println(factorial(n1)/(factorial(r1)*factorial(n1-r1)));System.out.println(factorial(n2)/(factorial(r2)*factorial(n2-r2)));}}