I am writing a program to generate all possible permutations of a given series of numbers and then generate all possible binary trees from that permutations so, what I thought is having a program which generates permutations and stores the result to a file and then write further code to read line by line (which has all permutations ) and generate binary trees out of them, so right now I have written half program which generates permutation and it stores the result in file.
#include <stdio.h>
//function to print the array
void printarray(int arr[], int size)
{
FILE *fp;
int i,j;
fp=fopen("result.txt","w");
for(i=0; i<size; i++)
{
// printf("%d ",arr[i]);
fprintf(fp,"%d ",arr[i]);
}
printf("
");
fclose(fp);
}
//function to swap the variables
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
//permutation function
void permutation(int *arr, int start, int end)
{
if(start==end)
{
printarray(arr, end+1);
return;
}
int i;
for(i=start;i<=end;i++)
{
//swapping numbers
swap((arr+i), (arr+start));
//fixing one first digit
//and calling permutation on
//the rest of the digits
permutation(arr, start+1, end);
swap((arr+i), (arr+start));
}
}
int main()
{
//taking input to the array
int size;
printf("Enter the size of array
");
scanf("%d",&size);
int i;
int arr[size];
for(i=0;i<size;i++)
scanf("%d",&arr[i]);
//calling permutation function
permutation(arr, 0, size-1);
return 0;
}
but the problem here in this program is that this program only stores one permutation and does not stores other permutations in result.txt file, how do I go on storing result this way. Also program does not ends a blank cursor blinking which gives a false impression of infinite while loop.
I had to press Ctrl+c to end the program how to get rid of this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…