I've been trying to work on a program that outputs only the existing words of all the possible permutations of n letters, for example:
Input "eta"
Output "tea, eat, ate"
As you can notice i don't want all the other permutations that are not words, such as "aet, tae"
For this purpose i have a dictionary.txt
I already have a function that prints all the possible permutations.
On the other hand i have a piece of code that compares a string with each line of my dictionary, and prints it if there's a match.
I just cannot manage to make both work together
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(char *a, int l, int r)
{
int encontrado=0;
int i;
if (l == r)
{
puts (a);
}
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i)); //backtrack
}
}
}
int main()
{
char str[60];
char str_mio[] = "aet";
int encontrado=0;
int n = strlen(str_mio);
permute(str_mio, 0, n-1);
FILE *fp;
fp = fopen("English.txt" , "r");
if(fp == NULL) {
perror("Error opening file");
return(-1);
}
else{
while( fgets (str, sizeof(str_mio), fp)!=NULL && encontrado!=1) {
//puts(str);
if(!strcmp(str,str_mio)){
puts(str_mio);
encontrado=1;
}
}
}
fclose(fp);
return 0;
}
Your
permute()routine outputs the string by directly callingputs(). Instead, you only want to output it if it's a match.Suppose you were to refactor the dictionary check code out of
main()into a new routineprintIfMatch(char *str_check)wherestr_checktakes the place of your current use ofstr_mioin the code inmain()Then you'd be able to call that routine from
permute()