Advertisement
STANAANDREY

comb tpa

Apr 14th, 2023 (edited)
1,021
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.04 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define CHECK_ALLOC(p) if (p == NULL) {perror(""); exit(-1);}
  4.  
  5. int *readArr(int *n) {
  6.   scanf("%d", n);
  7.   int *arr = (int*)malloc(sizeof(int) * *n);
  8.   CHECK_ALLOC(arr);
  9.   for (int i = 0; i < *n; i++) {
  10.     scanf("%d", arr + i);
  11.   }
  12.   return arr;
  13. }
  14.  
  15. void printArr(int arr[], int size) {
  16.   for (int i = 0; i < size; i++) {
  17.     printf("%d ", arr[i]);
  18.   }
  19.   printf("\n");
  20. }
  21.  
  22. void print_combinations(int arr[], int n, int k, int comb[], int start, int index, int *cnt) {
  23.   if (index == k) {
  24.     printf("#%d: ", ++*cnt);
  25.     printArr(comb, k);
  26.     return;
  27.   }
  28.   for (int i = start; i < n; i++) {
  29.     comb[index] = arr[i];
  30.     print_combinations(arr, n, k, comb, i + 1, index + 1, cnt);
  31.   }
  32. }
  33.  
  34. int main() {
  35.   int n, k;
  36.   int *arr = readArr(&n);
  37.   scanf("%d", &k);
  38.   int *comb = (int*)malloc(sizeof(int) * k);
  39.   if (!comb) {
  40.     free(arr);
  41.     perror("");
  42.     exit(-1);
  43.   }
  44.   int cnt = 0;
  45.   print_combinations(arr, n, k, comb, 0, 0, &cnt);
  46.   free(arr);
  47.   free(comb);
  48.   return 0;
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement