Skip to content

Instantly share code, notes, and snippets.

/dictionary.c Secret

Created September 12, 2016 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/dc5eb828e30199cd7f7ef60bb279b277 to your computer and use it in GitHub Desktop.
Save anonymous/dc5eb828e30199cd7f7ef60bb279b277 to your computer and use it in GitHub Desktop.
/**
* 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