I have completed the load() and check() function for pset5, however, I have been facing problems as some words are not identified as misspellings such as the words "org" and "int" which are not in the dictionary. My code is able to identify most of the misspelled words except for a few such as the two mentioned.
below are my load and check codes
/**
* Convert character to a number from 0 to 25
*/
int getIndex(char c)
{
if(c == '\'')
{
//last in dex to represent '\'''
return 26;
}
return c - 'a';
}
node* trieCreate() {
node *init = NULL;
init = malloc(sizeof(struct node));
if (init)
{
init->is_word = false;
memset(init->children, 0, sizeof(init->children));
}
return init;
}
/**
* Create a new child in the trie
*/
node* createChild()
{
node *temp = malloc(sizeof(node));
if (temp == NULL)
{
exit(1);
}
temp->is_word = false;
memset(temp->children, 0, sizeof(temp->children));
return temp;
}
/**
* Returns true if word is in dictionary else false.
*/
bool check(const char *word)
{
node *crawler = root;
bool flag = false;
//printf("%s\n", word);
// //check if word is NULL
if(!word)
{
return false;
}
//if word is empty
if (*word == '\0') {
return true;
}
int i=0, index =0 ;
while (word[i] != '\0')
{
index = getIndex(tolower(word[i]));
//printf("%c\n", word[i]);
//// if the node/character is not in Trie
if(crawler->children[index] == 0)
{
flag = false;
break;
}
if(word[i+1] != '\0')
{
crawler = crawler->children[index];
}
i++;
}
if(crawler->is_word == true && word[i] == '\0')
{
flag = true;
}
return flag;
}
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char *dictionary)
{
//Initialize dictionary
root = trieCreate();
FILE *inptr = fopen(dictionary, "r");
if(inptr == NULL)
{
printf("File could not be opened");
return false;
}
//traversal pointer
node *trav = root;
int index, i;
char word[LENGTH+1];
while(fgets(word, (LENGTH+1), inptr) != NULL)
{
i = 0;
//printf("%s\n", word);
trav = root;
while(word[i] != '\n')
{
if(isalpha(word[i]) || word[i] == '\'' || word[i] == '\n')
{
index = getIndex(tolower(word[i]));
//printf("%c: %d\n", word[i], index);
if(trav->children[index] == 0)
{
trav->children[index] = createChild();
}
if(word[i+1] == '\n'){
break;
}
trav = trav->children[index];
}
i++;
}
trav->is_word = true;
}
fclose(inptr);
return true;
}