// Implements a dictionary's functionality
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.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;
// TODO: Choose number of buckets in hash table
const unsigned int N = 26 * 26 * 26;
// Hash table
node *table[N];
int words = 0;
// Returns true if word is in dictionary, else false
bool check(const char *word)
{
// TODO
int hashed_word = hash(word);
node *cursor = table[hashed_word];
while (cursor != NULL)
{
if (strcasecmp(cursor->word, word) == 0)
{
return true;
}
else{
cursor = cursor->next;
return false;
}
}
return true;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
unsigned int index = 0;
// TODO: Improve this hash function
if (word[LENGTH + 1] < 3)
{
// hashes the first letter of a word when it has less than three letters
return toupper(word[0]) - 'A';
}
else if (word[LENGTH + 1] >= 3)
{
for (int i = 0; i < 3; i++)
{
// hash the first
if (isalpha(word[i]))
{
// hashes the first 3 letters of a word;
index += toupper(word[i] % 'A') * pow(26, 2 - i);
}
}
}
return index;
}
// Loads dictionary into memory, returning true if successful, else false
bool load(const char *dictionary)
{
// TODO
FILE *reader;
reader = fopen(dictionary, "r");
// open dictionary file
char buffer[LENGTH + 1];
// make buffer to read in
node *n = malloc(sizeof(node));
if (reader != NULL)
{
while (fscanf(reader, "%s", buffer) != EOF)
{
// read dictionary words into buffer
// make node
if (n == NULL)
{
// safety check
free(n);
return false;
}
// copy buffer into empty element in list
strcpy(n->word, buffer);
n->next = NULL;
int HASH = hash(buffer);
// hashed word is put into next node
n->next = table[HASH];
// point to next array element value
table[HASH] = n;
// update table
// close file
fclose(reader);
}
return true;
}
else
{
// if something goes wrong exit out program
free(n);
return false;
}
}
// Returns number of words in dictionary if loaded, else 0 if not yet loaded
unsigned int size(void)
{
// TODO
const char *dictionary;
bool loaded = !load(dictionary);
if (loaded == true)
{
for (int i = 0; i < N; i++)
{
while (table[i] != NULL)
{
words++;
table[i] = table[i]->next;
}
}
}
return 0;
}
// Unloads dictionary from memory, returning true if successful, else false
bool unload(void)
{
// TODO
for (int i = 0; i < N; i++)
{
node *cursor = table[i];
while (cursor != NULL)
{
node *tmp = cursor;
cursor = cursor->next;
free(tmp);
}
}
return true;
}