-
-
Save anonymous/dc5eb828e30199cd7f7ef60bb279b277 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* dictionary.c | |
* | |
* Computer Science 50 | |
* Problem Set 5 | |
* | |
* Implements a dictionary's functionality. | |
*/ | |
#include <stdbool.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include "dictionary.h" | |
/** | |
* Returns true if word is in dictionary else false. | |
*/ | |
bool check(const char* word) | |
{ | |
int word_hash_value = hash_it(word); | |
node* cursor = hashtable[word_hash_value]; | |
while (cursor != NULL) | |
{ | |
if (strcmp(cursor->word, word) == 0) return true; | |
else cursor = cursor->next; | |
} | |
return false; | |
} | |
/** | |
* Loads dictionary into memory. Returns true if successful else false. | |
*/ | |
bool load(const char* dictionary) | |
{ | |
// open dictionary | |
FILE* dic = fopen(dictionary, "r"); | |
if (dic == NULL) | |
{ | |
printf("Could not open dictionary."); | |
return 1; | |
} | |
// create nodes and put them into the hash table | |
while (1) | |
{ | |
// create a new node | |
node* new_node = malloc(sizeof(node)); | |
// put a word into the node | |
if (fscanf(dic, "%s", new_node->word) == EOF) return true; | |
// get hash value | |
int hash_val = hash_it(new_node->word); | |
// put the node into the hash table | |
if (hashtable[hash_val] == NULL) | |
{ | |
hashtable[hash_value] = new_node; | |
} | |
else | |
{ | |
new_node->next = hashtable[hash_value]; | |
hashtable[hash_value] = new_node; | |
} | |
// count the number of words in dictionary | |
count++ | |
} | |
return false; | |
} | |
/** | |
* Returns number of words in dictionary if loaded else 0 if not yet loaded. | |
*/ | |
unsigned int size(void) | |
{ | |
if (count != 0) return count; | |
else return 0; | |
} | |
/** | |
* Unloads dictionary from memory. Returns true if successful else false. | |
*/ | |
bool unload(void) | |
{ | |
for (int i = 0; i < 65536; i++) | |
{ | |
node* cursor = hashtable[i]; | |
while (cursor != NULL) | |
{ | |
node* temp = cursor; | |
cursor = cursor->next; | |
free(temp); | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment