Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- permutations_with_no_duplicates_v1.c
- https://www.codesdope.com/blog/article/generating-permutations-of-all-elements-of-an-arra/
- You can find all my C programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include <stdio.h>
- //function to print the array of n integers
- void print_array(int arr[], int n)
- {
- int i,j;
- printf("\n");
- for(i=0; i<n; i++)
- printf("%2d", arr[i]);
- printf("\n");
- }
- // function to swap the variables a and b
- void swap(int *a, int *b)
- {
- int temp;
- temp = *a;
- *a = *b;
- *b = temp;
- }
- // recursive function to generate permutation
- void permutation(int *arr, int start, int end)
- {
- int i;
- if(start==end)
- {
- print_array(arr, end+1); // this is one permutation
- return;
- }
- for( i=start; i<=end; i++ ) // fixing one first digit,
- {
- swap((arr+i), (arr+start)); // swapping numbers
- permutation(arr, start+1, end); // and calling permutation on the rest of the digits
- swap((arr+i), (arr+start)); // swapping numbers
- }
- } // permutation()
- int main(void)
- {
- int i, n;
- printf("Enter the size of array n = ");
- scanf("%d",&n);
- int arr[n]; // array of n permutation elements
- for (i = 0; i < n; i++) // fill in the array with integers from 1 to n
- arr[i] = i + 1;
- permutation(arr, 0, n-1); //calling recursive function to generate permutations
- return 0;
- } // main()
Advertisement
Add Comment
Please, Sign In to add comment