Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Implements a dictionary's functionality
- #include <ctype.h>
- #include <stdbool.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.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 = LENGTH;
- // Hash table
- node *table[N];
- // For size function
- int amount;
- // Loads dictionary into memory, returning true if successful, else false
- bool load(const char *dictionary)
- {
- char words[LENGTH + 1];
- int counter = 0;
- // Open dictionary file
- FILE *source = fopen(dictionary, "r");
- if (source == NULL)
- {
- return false;
- }
- // Read strings from file
- while (fscanf(source, "%s", words) != EOF)
- {
- // Create a new node
- node *n = malloc(sizeof(node));
- if (n == NULL)
- {
- return false;
- }
- // Fill in new node
- strcpy(n->word, words);
- n->next = NULL;
- // Find phrase bucket
- int bucket = hash(words);
- table[bucket] = malloc(sizeof(node));
- table[bucket]->next = NULL;
- // Insert node into hash table
- if (counter == 0)
- {
- table[bucket]->next = n;
- }
- else
- {
- n->next = table[bucket]->next;
- table[bucket]->next = n;
- }
- counter++;
- amount++;
- }
- // Close dictionary file
- fclose(source);
- return true;
- }
- // Hashes word to a number
- unsigned int hash(const char *word)
- {
- // TODO: Improve this hash function
- return strlen(word);
- }
- // Returns number of words in dictionary if loaded, else 0 if not yet loaded
- unsigned int size(void)
- {
- return amount;
- }
- // Returns true if word is in dictionary, else false
- bool check(const char *word)
- {
- // Create cursor
- node *cursor = malloc(sizeof(node));
- if (cursor == NULL)
- {
- return false;
- }
- // Hash word for value
- int value = hash(word);
- table[value] = malloc(sizeof(node));
- table[value]->next = NULL;
- // Access linked list at index
- cursor = table[value]->next;
- // Traverse linked list
- while (cursor != NULL)
- {
- if (strcasecmp(cursor->word, word) == 0)
- {
- return true;
- }
- else
- {
- cursor = cursor->next;
- }
- }
- return false;
- }
- // Unloads dictionary from memory, returning true if successful, else false
- bool unload(void)
- {
- node *cursor = malloc(sizeof(node));
- if (cursor == NULL)
- {
- return false;
- }
- node *tmp = malloc(sizeof(node));
- if (tmp == NULL)
- {
- return false;
- }
- for (int i = 0; i < LENGTH; i++)
- {
- table[i] = malloc(sizeof(node));
- table[i]->next = NULL;
- cursor = table[i]->next;
- tmp = cursor;
- while (cursor != NULL)
- {
- cursor = cursor->next;
- free(tmp);
- tmp = cursor;
- }
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment