I think I am almost finished with my speller program. It does print out misspelled words correctly, but it doesn't pass the check50, as the size function returns incorrect dictionary size. It fails all of the tests except for one, because the size function always returns expected quantity + 1. I am not sure where it gets this word from. The check for the maximum length work passes, which should give me a clue but it doesn't.
So, for the large dictionary size it should give me 143,091, but I get 143,092.
Can anybody please point me in the right direction?
Please see the code below:
// Implements a dictionary's functionality
#include <stdbool.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "dictionary.h"
void delete(treenode* del) {
if (!del)
return;
for (int i = 0; i < 27; i++) {
delete(del->letters[i]);
}
free(del);
}
unsigned int wordcounter;
// Returns true if word is in dictionary else false
bool check(const char *word)
{
treenode *check = root;
for (int i = 0; i < strlen(word); i++) {
int index;
if (word[i] == '\'') {
index = 26;
} else {
index = tolower(word[i]) - 'a';
}
if (check->letters[index] == NULL) {
return false;
} else {
check = check->letters[index];
}
if (i == (strlen(word) - 1)) {
if (check->is_word == false) {
return false;
}
}
}
return true;
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
wordcounter = 0;
root = malloc(sizeof(treenode));
FILE* dict = fopen(dictionary, "r");
if (!dict) {
printf("Could not open dictionary file\n");
return 1;
}
char word[46] = {0};
while (1) {
fgets(word, (LENGTH + 1), dict);
treenode *insert = root;
for (int i = 0; i < strlen(word); i++) {
int index = -1;
if (word[i] == '\'') {
index = 26;
} else if (word[i] >= 'a' && word[i] <= 'z') {
index = tolower(word[i]) - 'a';
}
if (index != -1) {
if (insert->letters[index] == NULL) {
insert->letters[index] = (treenode *)malloc(sizeof(treenode));
if(!insert->letters[index]) {
printf("Error allocating space for new node\n");
return 1;
}
insert = insert->letters[index];
for (int j = 0; j < 27; j++) {
insert->letters[j] = NULL;
}
} else {
insert = insert->letters[index];
}
}
if (i == (strlen(word) - 1)) {
insert->is_word = true;
if (root != insert && strlen(word) > 0) {
wordcounter++;
}
}
}
if (feof(dict))
break;
}
fclose(dict);
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
if (wordcounter >= 1)
return wordcounter;
return 0;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
delete(root);
return true;
}