Advertisement
STANAANDREY

perms tpa

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