Generate all combinations of a set in C

 

Objective

The objective of this program is to generate all possible combinations of a given set of elements. This is useful in various applications, such as combinatorial problems, decision-making processes, and generating subsets for algorithms.

Program Code


#include 

void generateCombinations(char *set, char *combination, int setLen, int combLen, int start) {
    // Print the current combination
    if (combLen > 0) {
        printf("%.*s\n", combLen, combination);
    }

    for (int i = start; i < setLen; i++) {
        combination[combLen] = set[i];
        generateCombinations(set, combination, setLen, combLen + 1, i + 1);
    }
}

int main() {
    char set[] = "abc"; // Input set
    int setLen = sizeof(set) - 1; // Length of the set (excluding null terminator)
    char combination[setLen + 1]; // Array to store combinations
    combination[0] = '\0'; // Initialize empty combination

    printf("All combinations of the set '%s':\n", set);
    generateCombinations(set, combination, setLen, 0, 0);

    return 0;
}
        

Explanation of the Program Structure

The program consists of a main function and a recursive function called generateCombinations. Here’s a breakdown of the program:

  • Headers and Function Declarations: The program includes the stdio.h header for input and output functions.
  • generateCombinations Function: This recursive function generates all combinations:
    • char *set: The input set of characters.
    • char *combination: The current combination being formed.
    • int setLen: The length of the input set.
    • int combLen: The current length of the combination.
    • int start: The starting index for the current combination generation.

    The function prints the current combination and recursively builds combinations by adding characters from the set.

  • main Function: The entry point of the program where the input set is defined and the recursive function is called.

How to Run the Program

  1. Copy the program code into a text editor and save it with a .c extension (e.g., combinations.c).
  2. Open a terminal or command prompt.
  3. Navigate to the directory where the .c file is saved.
  4. Compile the program using a C compiler (e.g., GCC):
    gcc combinations.c -o combinations
  5. Run the compiled program:
    ./combinations
  6. The program will output all combinations of the specified set.

 

Leave a Reply

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