Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Implements a dictionary's functionality
- #include <stdio.h>
- #include <stdbool.h>
- #include <stdlib.h>
- #include <strings.h>
- #include <string.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 = 17576;
- // Hash table
- node *table[N];
- // Assign qty of words imported from dictionary as a global value.
- int words = 0;
- // Returns true if word is in dictionary else false
- bool check(const char *word)
- {
- //maximum length of any word is 45 char so allocating space for 45 char
- char *lowerWord = malloc(45 * sizeof(char));
- // Change word to lower case for has table
- for (int i = 0, n = strlen(word); i < n; i++)
- {
- lowerWord[i] = tolower(word[i]);
- }
- int bucket = hash(lowerWord);
- node *cursor = table[bucket];
- //find matching word by traversing list one by one
- while(cursor != NULL)
- {
- if(strcasecmp((cursor -> word),word)== 0)
- {
- return true;
- }
- cursor = cursor -> next;
- }
- free(lowerWord);
- free(cursor);
- return false;
- }
- // Hashes word to a number
- // REFERENCE: https://twpower.github.io/160-hash-table-implementation-in-cpp-en
- unsigned int hash(const char *word)
- {
- int hash = 401;
- while (*word != '\0') {
- hash = ((hash << 4) + (unsigned int)(*word)) % N;
- word++;
- }
- return hash % N;
- }
- // 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 false;
- }
- char tempword[LENGTH + 1];
- int index = 0;
- //read strings from file
- while (fscanf(file, "%s", tempword)!= EOF)
- {
- // Determine hash
- unsigned int bucket = hash(tempword);
- //allocate new storage location to extend the list
- node *n = malloc(sizeof(node));
- if (n == NULL)
- {
- return false;
- }
- //write temp word to word paramter
- strcpy(n -> word, tempword);
- // revise pointers
- n -> next = table[bucket];
- table[bucket] = n;
- words++;
- //close file - finished manipulating it
- fclose(file);
- }
- if (words == 143091)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- // Returns number of words in dictionary if loaded else 0 if not yet loaded
- unsigned int size(void)
- {
- return words;
- }
- // Unloads dictionary from memory, returning true if successful else false
- bool unload(void)
- {
- for(int i = 0; i < N; i++)
- {
- node *cursor = table[i];
- node *temp = cursor;
- free(temp);
- cursor = cursor -> next;
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement