Advertisement
dmilicev

permutations_with_no_duplicates_v1.c

Apr 19th, 2020
518
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.52 KB | None
  1. /*
  2.  
  3.     permutations_with_no_duplicates_v1.c
  4.  
  5.     https://www.codesdope.com/blog/article/generating-permutations-of-all-elements-of-an-arra/
  6.  
  7.  
  8.     You can find all my C programs at Dragan Milicev's pastebin:
  9.  
  10.     https://pastebin.com/u/dmilicev
  11.  
  12. */
  13.  
  14. #include <stdio.h>
  15.  
  16. //function to print the array of n integers
  17. void print_array(int arr[], int n)
  18. {
  19.     int i,j;
  20.  
  21.     printf("\n");
  22.  
  23.     for(i=0; i<n; i++)
  24.         printf("%2d", arr[i]);
  25.  
  26.     printf("\n");
  27. }
  28.  
  29. // function to swap the variables a and b
  30. void swap(int *a, int *b)
  31. {
  32.     int temp;
  33.     temp = *a;
  34.     *a = *b;
  35.     *b = temp;
  36. }
  37.  
  38. // recursive function to generate permutation
  39. void permutation(int *arr, int start, int end)
  40. {
  41.     int i;
  42.  
  43.     if(start==end)
  44.     {
  45.         print_array(arr, end+1);        // this is one permutation
  46.         return;
  47.     }
  48.  
  49.     for( i=start; i<=end; i++ )         // fixing one first digit,
  50.     {
  51.         swap((arr+i), (arr+start));     // swapping numbers
  52.         permutation(arr, start+1, end); // and calling permutation on the rest of the digits
  53.         swap((arr+i), (arr+start));     // swapping numbers
  54.     }
  55. } // permutation()
  56.  
  57.  
  58. int main(void)
  59. {
  60.     int i, n;
  61.  
  62.     printf("Enter the size of array n = ");
  63.     scanf("%d",&n);
  64.  
  65.     int arr[n];                 // array of n permutation elements
  66.  
  67.     for (i = 0; i < n; i++)     // fill in the array with integers from 1 to n
  68.         arr[i] = i + 1;
  69.  
  70.     permutation(arr, 0, n-1);   //calling recursive function to generate permutations
  71.  
  72.     return 0;
  73. } // main()
Advertisement
RAW Paste Data Copied
Advertisement