// Implements a dictionary's functionality
#include <cs50.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.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;
// Declare hash table and variables
node *table[N];
int hash_value, words;
// Returns true if word is in dictionary, else false
bool check(const char *word)
{
hash_value = hash(word);
// Initialize cursor to the correct bucket in table
node *cursor = table[hash_value];
// Compare words cursor is pointing to with arg word, if match return true
while (cursor != 0)
{
if (strcasecmp(word, cursor->word) == 0)
{
return true;
}
// Move cursor to next word in bucket if no match
cursor = cursor->next;
}
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
// TODO: Improve this hash function
return toupper(word[0]) - 'A';
}
// Loads dictionary into memory, returning true if successful, else false
bool load(const char *dictionary)
{
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
return false;
}
char word[LENGTH + 1];
// Scans words, allocates memory and returns false if out of memory
while (fscanf(file, %s, word) != EOF)
{
node *n = malloc(sizeof(node));
if (n != NULL)
{
return false;
}
// Copies words into respective nodes and assigns hash values, building table
strcopy(n->word, word);
hash_value = hash(word);
n->next = table[hash_value];
table[hash_value] = n;
words++;
}
fclose(file);
return true;
}
// Returns number of words in dictionary if loaded, else 0 if not yet loaded
unsigned int size(void)
{
if (words > 0)
{
return words;
}
return 0;
}
// Unloads dictionary from memory, returning true if successful, else false
bool unload(void)
{
// TODO
for (int i = 0; i < N; i++)
{
// Initialize cursor at the first bucket
node *cursor = table[i];
// Iterate through words in bucket using temp variable to free after moving cursor
while (cursor != NULL)
{
node *tmp = cursor;
cursor = cursor->next;
free(tmp);
}
// Once out of words we begin the for loop again
if (cursor == NULL)
{
return true;
}
}
return false;
}