Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Implements a dictionary's functionality
- #include <stdbool.h>
- #include <stdio.h>
- #include <strings.h>
- #include <ctype.h>
- #include <stdlib.h>
- #include "dictionary.h"
- // Represents a node in a hash table
- typedef struct node
- {
- const char word[LENGTH+1];
- struct node *next;
- }
- node;
- // Dictionary size
- long dict_size = 0;
- // Number of buckets in hash table
- const unsigned int N = 33;
- // Hash table
- node *table[N] = {NULL};
- // Returns true if word is in dictionary, else false
- bool check(const char *word)
- {
- node *curr = table[hash(word)];
- while (curr != NULL)
- {
- if(strcasecmp(curr->word, word) == 0)
- return true;
- // Goes to the next element
- curr = curr->next;
- }
- return false;
- }
- // Hashes word to a number
- unsigned int hash(const char *word)
- {
- int c;
- long hash = 0;
- while ((c = *word++))
- {
- if (isupper(c))
- c -= 65;
- else if (islower(c))
- c -= 97;
- hash += c;
- }
- return hash % N;
- }
- // Loads dictionary into memory, returning true if successful, else false
- bool load(const char *dictionary)
- {
- FILE *file = fopen(dictionary, "r");
- char *word;
- while(fscanf(file, "%45s", word) == 1)
- {
- node *head = table[hash(word)];
- node *child = malloc(sizeof (node));
- child->next = head;
- child->word = word;
- table[hash(word)] = child;
- dict_size++;
- }
- return true;
- }
- // Returns number of words in dictionary if loaded, else 0 if not yet loaded
- unsigned int size(void)
- {
- return dict_size;
- }
- void unload_node(node *node)
- {
- if(node->next != NULL)
- unload_node(node->next);
- free(node);
- dict_size--;
- return;
- }
- // Unloads dictionary from memory, returning true if successful, else false
- bool unload(void)
- {
- return true;
- for(int i = 0; i < N; i++)
- {
- unload_node(table[i]);
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement