Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Implements a dictionary's functionality
- #include <stdbool.h>
- #include <strings.h>
- #include <string.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <ctype.h>
- #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 unsigned int N = 1000;
- // Hash table
- node *table[N];
- // Returns true if word is in dictionary else false
- bool check(const char *word)
- {
- node* temp = NULL;
- int h = hash(word);
- temp = table[h];
- do
- {
- int result = strcasecmp(word, temp->word);
- if (result == 0)
- {
- return true;
- break;
- }
- else
- {
- temp = temp->next;
- }
- }
- while (temp->next != NULL);
- return false;
- }
- /* Adapted by Neel Mehta from
- http://stackoverflow.com/questions/2571683/djb2-hash-function.
- */
- // Hashes word to a number
- unsigned int hash(const char *word)
- {
- unsigned long hash = 5381;
- for (const char* ptr = word; *ptr != '\0'; ptr++)
- {
- hash = ((hash << 5) + hash) + tolower(*ptr);
- }
- return hash % N;
- }
- // Loads dictionary into memory, returning true if successful else false
- int count;
- bool load(const char *dictionary)
- {
- FILE *dict = fopen(dictionary, "r");
- if (dict == NULL)
- {
- printf("Could not open dictionary.\n");
- return false;
- }
- char temp[46];
- count = 0;
- while (fscanf(dict, "%s", temp)!= EOF)
- {
- node* n = malloc(sizeof(node));
- if (n == NULL)
- {
- free(n);
- return false;
- }
- else
- {
- int h = hash(temp);
- strcpy(n->word, temp);
- n->next = table[h];
- table[h] = n;
- count++;
- }
- }
- fclose(dict);
- return true;
- }
- // Returns number of words in dictionary if loaded else 0 if not yet loaded
- unsigned int size(void)
- {
- if (!count || count == 0)
- {
- return 0;
- }
- else
- {
- return count;
- }
- }
- // Unloads dictionary from memory, returning true if successful else false
- bool unload(void)
- {
- node* temp = NULL;
- for (int i = 0; i <= N; i++)
- {
- temp = table[i];
- while (temp->next != NULL)
- {
- table[i] = temp->next;
- free(temp);
- temp = table[i];
- }
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement