How to generate all possible permutations and combinations of an array of chars in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
// Swap two chars
void swap(char *a, char *b) {
    char tmp = *a;
    *a = *b;
    *b = tmp;
}
 
// Print array of chars
void printArray(const char *arr, int size) {
    for (int i = 0; i < size; i++) {
        printf("%c ", arr[i]);
    }
    printf("\n");
}
 
// Recursive function to generate permutations
void permute(char *arr, int l, int r) {
    if (l == r) {
        printArray(arr, r + 1);
        return;
    }
    for (int i = l; i <= r; i++) {
        swap(&arr[l], &arr[i]);
        permute(arr, l + 1, r);
        swap(&arr[l], &arr[i]); // backtrack
    }
}
 
// Generate all combinations using bitmask
void generateCombinations(const char *arr, int size) {
    for (int mask = 1; mask < (1 << size); mask++) {
        for (int i = 0; i < size; i++) {
            if (mask & (1 << i)) {
                printf("%c ", arr[i]);
            }
        }
        printf("\n");
    }
}
 
int main() {
    char input[] = "abc";
    int size = strlen(input);
 
    printf("All permutations:\n");
    permute(input, 0, size - 1);
 
    printf("\nAll combinations:\n");
    generateCombinations(input, size);
 
    return 0;
}
 
 
  
/*
run:
    
All permutations:
a b c 
a c b 
b a c 
b c a 
c b a 
c a b 
 
All combinations:
a 
b 
a b 
c 
a c 
b c 
a b c 
    
*/

 



answered 1 day ago by avibootz
edited 16 hours ago by avibootz

Related questions

...