Implements a dictionary's functionality
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <strings.h>
#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 = 1;
Hash table
node *table[N];
Returns true if word is in dictionary else false
bool check(const char *word)
{
//change letters to lowercase
int length = strlen(word);
char copy[length + 1];
for (int i = 0; i < length; i++)
{
copy[i] = tolower(word[i]);
}
int copy_index = hash(copy);
//sed pointer to the head of linked list
node *head = table[copy_index];
node *cursor = head;
if (head != NULL)
{
while (cursor != NULL)
{
if (strcasecmp(copy,cursor -> word) == 0)
{
return true;
}
else
{
cursor = cursor -> next;
}
}
}
return false;
}
Hashes word to a number
unsigned int hash(const char *word)
{
// TODO
unsigned long hash = 5381;
int c;
while ((c = *word++))
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
FILE* source = fopen(dictionary , "r" );
// check the file is not empty
if (!source)
{
fprintf(stderr, "Couldn't open dictionary.\n");
return false;
}
char WORD[45];
int count = 0;
while (fscanf(source, "%s", WORD) != EOF)
{
struct node *wnode = malloc(sizeof(node));
if (wnode == NULL)
{
unload();
return false;
}
strcpy(wnode->word, WORD);
unsigned long key = hash(wnode->word);
//insert word into hash table. if first word of the linked list:
if(table[key] == NULL)
{
table[key] = wnode;
}
else
{
wnode->next = table[key];
table[key] = wnode;
}
}
return true;
}
Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
// TODO
return 0;
}
Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
for( int i = 0; i < N; i++)
{
node *head = table[i];
node *cursor = head;
if ( cursor != NULL)
{
node *tmp = cursor;
cursor = cursor -> next;
free(tmp);
}
}
return false;
}