Java Program to Generate All Combinations of a Set

 

 

Program Code


import java.util.ArrayList;
import java.util.List;

public class Combinations {

    // Method to generate all combinations of a set
    public static List<List> generateCombinations(List set) {
        List<List> result = new ArrayList<>();
        generateCombinations(set, 0, new ArrayList<>(), result);
        return result;
    }

    // Helper method for recursive combination generation
    private static void generateCombinations(List set, int index, List current, List<List> result) {
        // Add the current combination to the result
        result.add(new ArrayList<>(current));

        for (int i = index; i < set.size(); i++) {
            // Include set[i] in the current combination
            current.add(set.get(i));
            // Recur with the next index
            generateCombinations(set, i + 1, current, result);
            // Exclude the last added element (backtrack)
            current.remove(current.size() - 1);
        }
    }

    // Main method to test the combination generator
    public static void main(String[] args) {
        List set = List.of(1, 2, 3);
        List<List> combinations = generateCombinations(set);
        
        System.out.println("All combinations of the set " + set + ":");
        for (List combination : combinations) {
            System.out.println(combination);
        }
    }
}

Program Explanation

This Java program generates all combinations of a given set of integers. The main components of the program are as follows:

  • Import Statements:We import ArrayList and List from the java.util package to utilize dynamic arrays.
  • Class Definition:The Combinations class contains methods for generating combinations.
  • generateCombinations Method:This method initializes the combination generation process. It takes a list of integers as input and calls a helper method.
  • Helper Method:The generateCombinations method is a recursive function that builds combinations by including or excluding each element. It maintains the current state of the combination in the current list and adds it to the result list.
  • Backtracking:After each recursive call, we backtrack by removing the last added element from the current combination. This allows us to explore other possible combinations.
  • Main Method:The main method serves as the entry point of the program. It initializes a sample set, calls the combination generator, and prints the results to the console.

Usage

To run this program, copy the code into a Java development environment, compile it, and execute the main method. The output will display all possible combinations of the given set.

 

Leave a Reply

Your email address will not be published. Required fields are marked *