fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void combinations(int **sets, int *sizes, int *indices, int n, int depth, int *output, int *count) {
  5. if (depth == n) {
  6. // base case: we have selected one element from each set
  7. // print the combination
  8. for (int i = 0; i < n; i++) {
  9. printf("%d", sets[i][indices[i]]);
  10. }
  11. printf("\n");
  12. // add the combination to the output array
  13. for (int i = 0; i < n; i++) {
  14. output[*count * n + i] = sets[i][indices[i]];
  15. }
  16. (*count)++;
  17. return;
  18. }
  19. // recursive case: select one element from the current set and move on to the next set
  20. for (int i = 0; i < sizes[depth]; i++) {
  21. indices[depth] = i;
  22. combinations(sets, sizes, indices, n, depth + 1, output, count);
  23. }
  24. }
  25.  
  26. int main() {
  27. int n = 2;
  28. int *sizes = malloc(n * sizeof(int));
  29. sizes[0] = 3;
  30. sizes[1] = 2;
  31. int **sets = malloc(n * sizeof(int *));
  32. sets[0] = malloc(3 * sizeof(int));
  33. sets[0][0] = 1;
  34. sets[0][1] = 2;
  35. sets[0][2] = 3;
  36. sets[1] = malloc(2 * sizeof(int));
  37. sets[1][0] = 2;
  38. sets[1][1] = 5;
  39. int *indices = calloc(n, sizeof(int));
  40. int count = 0;
  41. int *output = malloc(n * sizes[0] * sizes[1] * sizeof(int));
  42. combinations(sets, sizes, indices, n, 0, output, &count);
  43. printf("Total combinations: %d\n", count);
  44. for (int i = 0; i < count; i++) {
  45. for (int j = 0; j < n; j++) {
  46. printf("%d", output[i * n + j]);
  47. }
  48. printf("\n");
  49. }
  50. free(sizes);
  51. free(sets[0]);
  52. free(sets[1]);
  53. free(sets);
  54. free(indices);
  55. free(output);
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0s 5456KB
stdin
Standard input is empty
stdout
12
15
22
25
32
35
Total combinations: 6
12
15
22
25
32
35