Advertisement
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 "dictionary.h"
- int dictionary_size = 0;
- typedef struct node
- {
- char word[LENGTH + 1];
- struct node* next;
- }
- node;
- // set array to be the size of words in large dictionary
- node *hashtable[143091];
- // hashing new_node->word will give index of a bucket in the hash table
- // https://stackoverflow.com/questions/7666509/hash-function-for-string
- // http://www.cse.yorku.ca/~oz/hash.html
- unsigned int hash_word(const char* word)
- {
- unsigned long hash = 5381;
- for (const char* ptr = word; *ptr != '\0'; ptr++)
- {
- hash = ((hash << 5) + hash) + tolower(*ptr);
- }
- return (hash % 143091);
- }
- // Returns true if word is in dictionary else false
- bool check(const char *word)
- {
- // format word to wordf
- int len = strlen(word);
- char wordf[len + 1];
- for (int i = 0; i < len; i++)
- {
- wordf[i] = tolower(word[i]);
- }
- wordf[len] = '\0';
- // get hash value for "bucket"
- int hash = hash_word(wordf);
- // assign cursor node to the first node of the bucket
- node* cursor = hashtable[hash];
- while (cursor != NULL)
- {
- if (strcmp(cursor->word, wordf) == 0)
- {
- return true;
- }
- else
- {
- cursor = cursor->next;
- }
- }
- return false;
- }
- // Loads dictionary into memory, returning true if successful else false
- bool load(const char *dictionary)
- {
- FILE* source = fopen(dictionary, "r");
- if (source == NULL)
- {
- fprintf(stderr, "Could not open dictionary.\n");
- return false;
- }
- char word[LENGTH + 1];
- while(fscanf(source, "%s", word) != EOF)
- {
- node *new_node = malloc(sizeof(node));
- if (new_node == NULL)
- {
- unload();
- fprintf(stderr, "Out of memory.\n");
- return false;
- }
- dictionary_size++;
- strcpy(new_node->word, word);
- int hashed = hash_word(new_node->word);
- node *head = hashtable[hashed];
- new_node->next = head;
- hashtable[hashed] = new_node;
- }
- fclose(source);
- return true;
- }
- // Returns number of words in dictionary if loaded else 0 if not yet loaded
- unsigned int size(void)
- {
- return dictionary_size;
- }
- // Unloads dictionary from memory, returning true if successful else false
- bool unload(void)
- {
- for (int i = 0; i < 143091; i++)
- {
- node *cursor = hashtable[i];
- while (cursor != NULL)
- {
- node *temp = cursor;
- cursor = cursor->next;
- free(temp);
- }
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement