所以这个程序应该整理一个单词以显示相同长度的有效单词。这是一项需要在函数内进行动态内存分配的任务,并且变得相当混乱。在程序开始时,我必须为长度为 n 的字典动态分配内存。我们得到的字典长度为 10000,单词的最大长度为 20 个字符。我选择动态创建每个单词的排列数组,然后将它们与字典中的单词进行比较,使用 strcmp 进行二进制搜索(用户和字典中输入的所有单词都是大写字母,因此这是一种可行的方法)。整个程序通过第一次迭代减去作为有效单词的重复排列和 while 循环过早退出。
其他一些规格:
- 用户输入“y”或“Y”表示他们想玩
我没有尝试任何方法来解决这个问题,因为我想不出一个 while 循环会退出的任何原因。特别是因为即使我不允许扫描新值,选择仍应为“y”或“Y”。
这是主要的。
int main() {
char** dictionary;
int num_words;
// defined FILE* outside of file read in function to avoid returning local variable address
FILE* ifp = fopen("Dictionary.txt", "r");
fscanf(ifp, "%d", &num_words);
dictionary = FileReadIn(num_words, ifp);
char choice = Welcome();
// main part of program Im unsure why it exits after its first iteration
while ((choice == 'y') || (choice == 'Y')) {
char* letters = LettersReadIn();
// Calculates number of permutations which is (numletters)!
long num_permutations = Factorial(strlen(letters));
// Sets up permutations through malloc
char** permutations = (char**)malloc((num_permutations) * sizeof(char*));
int i;
for (i = 0; i < num_permutations; i++) {
permutations[i] = (char*)malloc(MAXWORDLENGTH * sizeof(char));
}
// Creates all permutations of the letters entered in by the user in a recursive function
RecursivePermute(letters, 0, permutations);
// Created the WordIndices array in order to keep track of which indices in the permutations array are valid words
// Could not get the program to work when I created wordindices in Viable Words
// Viable Words checks each permutation against words in the dictionary using a binary search
// which compared each word lexicographically with strcmp
int* word_indices = (int*)malloc(num_permutations * sizeof(int));
ViableWords(permutations, dictionary, num_permutations, num_words, word_indices);
// Prints each index in permutations that is a valid word
// valid word indices stored in word indices
PrintWords(permutations, num_permutations, letters, word_indices);
// frees permutations and word indices
free(permutations);
free(word_indices);
choice = Welcome();
} // End While loop
return 0;
} // End main
这就是欢迎功能。
char Welcome() {
printf("Welcome to the Jumble Puzzle Solver!\n");
printf("Would you like to enter a jumbled word?\n");
char choice;
scanf("%c", &choice);
return choice;
}// End Welcome
所以基本上我的问题是为什么会导致这种情况发生,什么是解决方案。
如果您需要任何其他信息,请告诉我,如果您发现任何其他需要改进的地方,请告诉我。我对编程还很陌生,所以我喜欢一些建设性的批评。