Header Ads Widget

Responsive Advertisement

Custom Combination and permutation program

The concepts of combinations and permutations stem from combinatorial mathematics, with roots tracing back to ancient mathematics. They were formally introduced as part of probability and combinatorial analysis:

Ø  Ancient Roots: In ancient Greece, mathematicians like Aristotle explored basic ideas of arranging and choosing objects. In India, mathematicians such as Pingala developed concepts in combinatorics, focusing on binary combinations of syllables.

Ø  Formal Development in the 17th Century: Blaise Pascal and Pierre de Fermat contributed foundational ideas in combinatorics, particularly in probability, leading to more structured studies of arrangements and choices.

Ø  Modern Uses: In the 20th and 21st centuries, combinations and permutations became fundamental to fields such as computer science, cryptography, machine learning, operations research, and statistical theory.

What Are Combinations and Permutations?

Ø  Permutations: An arrangement of objects in a specific order. The order in permutations matters, so ABC is different from CBA.

Ø  Combinations: A selection of objects without regard to order. For example, in combinations, ABC is the same as CBA.

Uses of Combination and Permutation Programs

Combination and permutation calculations are essential for tasks involving probability, optimization, and data analysis, among others.

1. Data Science and Machine Learning

Ø  Feature Selection: Combinations are often used to choose subsets of features for machine learning models.

Ø  Parameter Optimization: Permutations allow for testing all possible arrangements of parameters for tuning models.

2. Probability and Statistics

Ø  Lottery and Gambling: Calculating winning odds by analyzing all possible number combinations.

Ø  Survey Sampling: Determining possible groups from larger populations.

3. Cryptography

Ø  Password Cracking: Permutation algorithms help to analyze all possible password combinations in brute-force attacks.

Ø  Encryption Algorithms: The design of algorithms that rely on arrangements of key characters.

4. Operations Research and Optimization

Ø  Route Optimization: Permutations help calculate all possible routes in logistics, aiding in the shortest path or traveling salesman problems.

Ø  Resource Allocation: Selecting optimal combinations of resources to minimize costs or maximize efficiency.

5. Game Theory and Puzzle Solving

Ø  Chess and Puzzles: Calculating possible move sequences or arrangements.

Ø  Card Games: Estimating winning strategies by analyzing card combinations and possible moves.

6. Programming and Software Testing

Ø  Test Case Generation: Combinations generate potential test case scenarios to ensure comprehensive software testing.

Ø  Algorithm Design: Recursive algorithms often use combinatorial principles to solve complex problems.

Sample Combination and Permutation Programs in Java

Here are simple examples of permutation and combination calculations in java:

This Java program generates permutations of a given set of elements and demonstrates how to calculate permutation subsets of both integers and characters.

Key Features of the Code:

  1. Generic Permutations Class:

Ø  The Permutations<T> class is generic, which allows it to handle any type of data (e.g., integers, strings).

Ø  The permute method takes a collection of elements and recursively generates all possible permutations.

  1. Handling Different Data Types:

Ø  The code first handles integer permutations (input with values 1, 2, 3) and then string permutations (inputStr with values "K", "A", "R", "T").

  1. Subset Generation:

Ø  After generating all permutations, the code creates subsets from the permutations by taking sublists of different lengths (subList(i, integers.size())).

Breakdown of the Key Methods:

1. permute(Collection<T> input):

Ø  This is the core method that recursively generates all permutations of the input collection.

Ø  It works by fixing one element (the head), and then recursively permuting the rest of the elements (rest).

Ø  For each permutation of the rest, the head is inserted at every possible position in the list.

2. Subset Generation:

Ø  After the permutations are generated, the code extracts sublists from each permutation, generating subsets of varying lengths.

Ø  This step essentially calculates P(n,k) (permutations of n elements taken k at a time).

Code Walkthrough:

java

package com.kartik;

 

import java.util.ArrayList;

import java.util.Collection;

import java.util.HashSet;

import java.util.List;

import java.util.Set;

 

/**

 * A class that generates permutations of a given input set.

 *

 * @author kartik

 */

public class Permutations<T> {

 

    public static void main(String args[]) {

        System.out.println("Integer permutation below:");

       

        // Integer permutation

        Permutations<Integer> obj = new Permutations<Integer>();

        Collection<Integer> input = new ArrayList<Integer>();

        input.add(1);

        input.add(2);

        input.add(3);

 

        // Generate permutations

        Collection<List<Integer>> output = obj.permute(input);

        int k = 0;

        Set<List<Integer>> pnr = null;

 

        // Loop over the size of the input

        for (int i = 0; i <= input.size(); i++) {

            pnr = new HashSet<List<Integer>>();

            for (List<Integer> integers : output) {

                // Create subsets of size (n - i)

                pnr.add(integers.subList(i, integers.size()));

            }

            k = input.size() - i;

            System.out.println("P(" + input.size() + "," + k + ") :" + "Count (" + pnr.size() + ") :- " + pnr);

        }

 

        System.out.println("Character permutation and combination below:");

 

        // String permutation

        Permutations<String> objStr = new Permutations<String>();

        Collection<String> inputStr = new ArrayList<String>();

        inputStr.add("K");

        inputStr.add("A");

        inputStr.add("R");

        inputStr.add("T");

 

        // Generate permutations for string input

        Collection<List<String>> outputStr = objStr.permute(inputStr);

        int len = 0;

        Set<List<String>> pnrStr = null;

 

        // Loop over the size of the input string

        for (int i = 0; i <= inputStr.size(); i++) {

            pnrStr = new HashSet<List<String>>();

            for (List<String> integers : outputStr) {

                // Create subsets of size (n - i)

                pnrStr.add(integers.subList(i, integers.size()));

            }

            len = inputStr.size() - i;

            if (i == 0) {

                System.out.println("P(" + inputStr.size() + "," + len + ") :" + "Count (" + pnrStr.size() + ") :- " + pnrStr);

            }

        }

    }

 

    /**

     * Recursive method to generate permutations of the input collection.

     *

     * @param input The input collection of elements.

     * @return A collection of lists representing all permutations.

     */

    public Collection<List<T>> permute(Collection<T> input) {

        Collection<List<T>> output = new ArrayList<List<T>>();

       

        // Base case: if the input is empty, return an empty list

        if (input.isEmpty()) {

            output.add(new ArrayList<T>());

            return output;

        }

 

        // Convert input to a list and get the first element (head)

        List<T> list = new ArrayList<T>(input);

        T head = list.get(0);

        List<T> rest = list.subList(1, list.size());

 

        // Recursive call to permute the rest of the elements

        for (List<T> permutations : permute(rest)) {

            List<List<T>> subLists = new ArrayList<List<T>>();

 

            // Insert the head element at each possible position in the current permutation

            for (int i = 0; i <= permutations.size(); i++) {

                List<T> subList = new ArrayList<T>();

                subList.addAll(permutations);

                subList.add(i, head);

                subLists.add(subList);

            }

            output.addAll(subLists);

        }

        return output;

    }

}

 In this example:

Ø  Permutation (nPr): The function calculates the number of ways to arrange r items out of n distinct items.

Ø  Combination (nCr): The function calculates the number of ways to select r items from n distinct items, disregarding order.

Explanation of Code:

  1. Integer Permutation:

Ø  The code generates all possible permutations of integers [1, 2, 3].

Ø  It then calculates subsets of varying lengths (from P(3,3) down to P(3,0)).

  1. String Permutation:

Ø  Similarly, for the string input "KART", the code generates all permutations.

Ø  It calculates subsets based on the generated permutations.

  1. Permutation Logic:

Ø  For each recursive call, the first element (head) is fixed, and all permutations of the remaining elements (rest) are generated.

Ø  The head is then inserted at all possible positions within each permutation of rest, resulting in new permutations.

Sample Output:

For the integer permutation of [1, 2, 3], you'll get output like:

P(3,3) : Count (1) :- [[1, 2, 3]]

P(3,2) : Count (3) :- [[2, 3], [1, 3], [1, 2]]

P(3,1) : Count (3) :- [[3], [2], [1]]

P(3,0) : Count (1) :- [[]]

 

For the string permutation of "KART", the output will look like:

P(4,4) : Count (1) :- [[K, A, R, T]]

P(4,3) : Count (4) :- [[A, R, T], [K, R, T], [K, A, T], [K, A, R]]

P(4,2) : Count (6) :- [[R, T], [A, T], [A, R], [K, T], [K, R], [K, A]]

P(4,1) : Count (4) :- [[T], [R], [A], [K]]

P(4,0) : Count (1) :- [[]]

 

Performance Considerations:

Ø  The algorithm generates all permutations recursively, making it O(n!), where n is the size of the input. Be cautious with large input sizes due to the exponential growth in the number of permutations.

You can adjust the input sets (e.g., add more characters or integers) to explore different combinations and permutations.

Permutation and Combination Calculator

Enter values for n and r:


Permutations (nPr):

Combinations (nCr):

 

 

For more information, visit

Ø  Pascal Triangle

For Other information, visit

Ø  Microservices: Custom Filters for Debouncing, Throttling, Rate Limits & Backoff

Ø  Mastering Debouncing, Throttling, Rate Limiting, and Exponential Backoff.

Ø  Custom Filters in Microservices

Ø  Spring Cloud Gateway uses a RewritePath filter

Ø  OAuth 2.0 Grant Types & Related Concepts Overview

Post a Comment

1 Comments

Kartik Chandra Mandal
amit singh rana said…
Hi Kartik, It is good that you share java code and solutions with others. keep it up.
One advice to you that use some good font so it will be visible.