edit 1: Here's a pic of the IDE
// Implements a dictionary's functionality
#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 int N = 65536;
// Hash table
node *table[N];
// Returns true if word is in dictionary else false
bool check(const char *word)
{
// Hash to obtain a hash value
int index = hash(word);
node *cursor = malloc(sizeof(node));
// Access linked list at that index in the hash table
while (cursor != NULL)
{
cursor = table[index];
// Traverse linked list, looking for the word
if (strcasecmp(cursor->word, word) == 0)
{
return 0;
}
else
{
cursor = cursor->next;
}
}
return 1;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
unsigned int hash = 0;
for (int i = 0, n = strlen(word); i < n; i++)
{
hash = (hash << 2) ^ word[i];
}
return hash % N;
}
// Counter for words in table
int counter = 0;
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
// Open dictionary file
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
return 1;
}
// Read stings from the file, one at a time
char word[LENGTH + 1];
int index;
while (fscanf(file, "%s", word) != EOF)
{
index = hash(word);
node *n = malloc(sizeof(node));
if (n == NULL)
{
free(n);
return 1;
}
strcpy(n->word, word);
if (table[index] == NULL)
{
table[index] = n;
n->next = NULL;
}
else
{
n->next = table[index];
table[index] = n;
}
counter++;
free(n);
}
fclose(file);
return 0;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
// TODO
if (counter > 0)
{
return counter;
}
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];
do
{
node *tmp = cursor;
cursor = tmp->next;
free(tmp);
}
while (cursor != NULL);
free(cursor);
free(table);
return true;
}
return false;
}