Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,933 questions

51,870 answers

573 users

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 84 views
1 answer 157 views
1 answer 100 views
1 answer 191 views
1 answer 172 views
1 answer 132 views
...