// Implements a dictionary's functionality #include #include #include #include #include #include #include "dictionary.h" // Represents a node in a hash table typedef struct node { char word[LENGTH + 1]; struct node *next; } node; // Number of buckets in hash table const unsigned int N = 50000; // Hash table node *table[N]; // Returns true if word is in dictionary else false bool check(const char *word) { int index = hash(word); for (node *cursor = table[index]; cursor != NULL; cursor = cursor->next) { int check = strcasecmp(cursor -> word, word); if(check == 0) { return true; } } return false; } // Hashes word to a number // this hash function is based on a hash function called djb2 and it is from http://www.cse.yorku.ca/~oz/hash.html unsigned int hash(const char *word) { unsigned long hash = 5381; int c; while ((c = *word++)) { hash = ((hash << 5) + hash) + tolower(c); } return hash % N; } // Loads dictionary into memory, returning true if successful else false bool load(const char *dictionary) { char word[LENGTH + 1]; FILE *file = fopen(dictionary, "r"); if (!file) { return false; } while (fscanf(file, "%s", word) != EOF) { int index = hash(word); node *new_ = malloc(sizeof(node)); if (new_ == NULL) { return 1; } strcpy(new_->word, word); new_->next= table[index]; new_ = table[index] ; } fclose(file); return true; } // Returns number of words in dictionary if loaded else 0 if not yet loaded unsigned int size(void) { int count = 0; for (int o = 0; o< N;o++) { for (node *temp = table[o]; temp != NULL; temp = temp->next) { count ++; temp = temp -> next; } } return count; } // Unloads dictionary from memory, returning true if successful else false bool unload(void) { for (int o = 0; o< N;o++) { node *cursor2 = table[o]; while(cursor2 != NULL) { node *temp = cursor2; cursor2 = cursor2->next; free(temp); } } return true; }