How to generate N combinations of X numbers in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
 
void printCombination(int arr[], int size, int combinations, int resi, int result[], int arri) {
    if (resi == combinations) {
        for (int j = 0; j < combinations; j++) {
            printf("%d ", result[j]);
        }
        printf("\n");
        return;
    }
 
    if (arri >= size) {
        return;
    }
 
    result[resi] = arr[arri];
    printCombination(arr, size, combinations, resi + 1, result, arri + 1);
 
    printCombination(arr, size, combinations, resi, result, arri + 1);
}
 
int generateCombinations(int arr[], int size, int combinations) {
    int *result = (int*)malloc(size * sizeof(int));
      
    if (result == NULL) {
        return -1;
    }
    
    printCombination(arr, size, combinations, 0, result, 0);
     
    free(result);
     
    return 1;
}
 
int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int combinations = 3;
    int size = sizeof(arr) / sizeof(arr[0]);
     
    generateCombinations(arr, size, combinations);
     
    return 0;
}
 
 
/*
run:
 
1 2 3 
1 2 4 
1 2 5 
1 3 4 
1 3 5 
1 4 5 
2 3 4 
2 3 5 
2 4 5 
3 4 5 
 
*/

 



answered Sep 24, 2024 by avibootz
edited Sep 24, 2024 by avibootz

Related questions

1 answer 103 views
1 answer 180 views
1 answer 119 views
1 answer 234 views
1 answer 219 views
1 answer 162 views
...