I have to find a combination of groups of letters, second letter in first group should be the same as first letter in second group etc.
For example, solution for this group: AA, CB, AC, BA, BD, DB is this: CB, BD, DB, BA, AA, AC
I have this code so far, it works, but if there is a lot of groups, it takes ages to compute. I need to make it more efficient.
In the input file, there's this input
10
C D
B C
B B
B B
D B
B B
C A
A B
B D
D C
My code
Code:
#include<stdlib.h>
void permutation(char group[][2],int buffer,int sum){
int i, j;
char temp;
if(buffer == sum && group[1][1]== group[sum][2]){
for(i =1; i < sum; i++)
if(group[i][2]!= group[i+1][1])break;
if(i == sum){
FILE*output;
output = fopen("output.txt","a");
for(j =1; j <= sum; j++){
fprintf(output,"%c %c\n", group[j][1], group[j][2]);
}
exit(1);
}
}else{
for(i = buffer; i <= sum; i++){
temp = group[buffer][1];
group[buffer][1]= group[i][1];
group[i][1]= temp;
temp = group[buffer][2];
group[buffer][2]= group[i][2];
group[i][2]= temp;
permutation(group, buffer +1, sum);
temp = group[buffer][1];
group[buffer][1]= group[i][1];
group[i][1]= temp;
temp = group[buffer][2];
group[buffer][2]= group[i][2];
group[i][2]= temp;
}
}
}
int main(){
FILE*input;
input = fopen("input.txt","r");
int sum, i;
fscanf(input,"%d",&sum);
char group[sum][2];
for(i =1; i <= sum; i++){
fscanf(input,"%s",&group[i][1]);
fscanf(input,"%s",&group[i][2]);
}
permutation(group,1, sum);}