Permutation and Combination in Java

Java 8Object Oriented ProgrammingProgramming

Permutation and Combination are a part of Combinatorics. Permutation is the different arrangements that a set of elements can make if the elements are taken one at a time, some at a time or all at a time. Combination is is the different ways of selecting elements if the elements are taken one at a time, some at a time or all at a time.

An example of this is given as follows −

Permutation = factorial(n) / factorial(n-r);
Combination =  factorial(n) / (factorial(r) * factorial(n-r));
n = 5
r = 3
Permutation = 60
Combination = 10

A program that demonstrates this is given as follows −

Example

Live Demo

public class Example {
   static int factorial(int n) {
      int fact = 1;
      int i = 1;
      while(i <= n) {
         fact *= i;
         i++;
      }
      return fact;
   }
   public static void main(String args[]) {
      int n = 7, r = 3, comb, per;
      per = factorial(n) / factorial(n-r);
      System.out.println("Permutation: " + per);
      comb = factorial(n) / (factorial(r) * factorial(n-r));
      System.out.println("Combination: " + comb);
   }
}

The output of the above program is as follows −

Output

Permutation: 210
Combination: 35

Now let us understand the above program.

The function factorial finds the factorial of the number n using a while loop. Then it returns fact. The code snippet that demonstrates this is given as follows −

static int factorial(int n) {
   int fact = 1;
   int i = 1;
   while(i <= n) {
      fact *= i;
      i++;
   }
   return fact;
}

In the function main(), the permutation and combination of n and r are found using their respective formulas. Then the results are displayed. The code snippet that demonstrates this is given as follows −

public static void main(String args[]) {
   int n = 7, r = 3, comb, per;
   per = factorial(n) / factorial(n-r);
   System.out.println("Permutation: " + per);
   comb = factorial(n) / (factorial(r) * factorial(n-r));
   System.out.println("Combination: " + comb);
}
raja
Published on 10-Dec-2018 07:11:30
Advertisements