Check50 returns all happy faces but my program doesn't find as many mispelled words as it should.
I'm not sure if the problem is my check function or my load function
I tried checking witih debug50 and different dictionaries and texts but it's annoying because it works well with small texts and dictionaries, but as soon as they get long it starts skipping words
unsigned int get_index(char c)
{
if (isalpha(c))
{
return (tolower(c) - 'a');
}
else
{
return 26; // Index 26 \ (backslash)
}
}
// Loads dictionary into memory, returning true if successful else false using TRIE
bool load(const char *dictionary)
{
// Open dictionary
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
unload();
return false;
}
// Initialize root node
root = calloc(1, sizeof(node)); // Calloc sets every pointer to NULL
root -> is_word = false;
// Buffer for a word
char word[LENGTH + 1];
// Insert words into trie, scans the dictinary word by word
while (fscanf(file, "%s", word) != EOF)
{
// Increase count for size function
count++;
// To know what's the number for that letter of the alphabet
int index = 0;
// To traverse the trie
node *trav = root;
node *local_root = root; // Just for debugging
// Loop to iterate every character in the word
for (int j = 0, word_len = strlen(word); j < word_len; j++)
{
index = get_index(word[j]);
// If the letter hasn't been stored before
if (trav -> children[index] == NULL)
{
// Create a new child node
node *new_children = calloc(1, sizeof(node));
// Point the previous node letter to the new child node
trav -> children[index] = new_children;
// If it's the end of the word, set the boolean to true
if (j == (word_len - 1))
{
trav -> is_word = true;
}
// Point the traversal node to the new child
trav = new_children;
}
// If the letter is already stored
else
{
// Point the traversal node to the next correspondent node
trav = trav -> children[index];
}
}
}
// Close dictionary
fclose(file);
// Indicate success
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
return count;
}
// Returns true if word is in dictionary else false
bool check(const char *word)
{
node *trav = root;
// For each letter in word
for (int i = 0, word_len = strlen(word); i < word_len; i++)
{
// Go to corresponding element in children
int index = get_index(word[i]);
// If NULL, word is mispelled
if (trav == NULL || trav -> children[index] == NULL)
{
return false;
}
// Once at end of word, check if word is true
else if (i == (word_len - 1))
{
if (trav -> is_word == true)
{
return true;
}
else
{
return false;
}
}
trav = trav -> children[index];
}
return true;
}