Printing all permutations of n numbers
Print all n! permutations of the number 1,2,3,...,n.
Example: Input: 3
Output: 1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
Following is my approach. My program is not working for inputs greater than 3. I understand the logic why it is not working , but I am unable to translate that logic into a code block to overcome that issue.
#include <stdio.h>
int permute(int n)
{
int a[n];
int i,j,k,store;
for(i=0;i<n;i++)
a[i]=i+1;
for(i=1;i<=n;i++)
{
for(j=0;j<n-1;j++)
{
store=a[j+1];
a[j+1]=a[j];
a[j]=store;
for(k=0;k<n;k++)
printf("%d ",a[k]);
printf("\n");
}
}
}
int main()
{
int n;
scanf("%d",&n);
permute(n);
return 0;
}
Following is the output for n as 4:
We can clearly see that some permutation are missing, and I know exactly the fault in my code. But I am unable to fix it.( I am a beginner , hence I don't know much advanced C libraries or functions)
One solution consists in calling the function recursively: you set the first number (n
possible choices), then call the function for a size n-1
.
Output, for n=4
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 3 2
1 4 2 3
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 3 1
2 4 1 3
3 2 1 4
3 2 4 1
3 1 2 4
3 1 4 2
3 4 1 2
3 4 2 1
4 2 3 1
4 2 1 3
4 3 2 1
4 3 1 2
4 1 3 2
4 1 2 3
#include <stdio.h>
#include <stdlib.h>
void swap (int *i, int *j) {
int temp = *i;
*i = *j;
*j = temp;
}
void permute(int index, int* arr, int n) {
if (index == n-1) {
for (int k = 0; k < n; ++k) {
printf ("%d ", arr[k]);
}
printf ("\n");
return;
}
for (int i = index; i < n; i++) {
swap (arr + index, arr + i);
permute (index+1, arr, n);
swap (arr + i, arr + index);
}
return;
}
int main()
{
int n;
if (scanf("%d",&n) != 1) exit (1);
int arr[n];
for (int i = 0; i < n; ++i) arr[i] = i+1;
permute(0, arr, n);
return 0;
}