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 <string.h>
- #include <strings.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include "dictionary.h"
- // Represents a node in a hash table
- typedef struct node
- {
- char word[LENGTH + 1];
- struct node *next;
- }
- node;
- // variables
- unsigned int counter;
- unsigned int word_count = 0;
- // TODO: Choose number of buckets in hash table
- const unsigned int N = 26;
- // Hash table
- node *table[N];
- // Returns true if word is in dictionary, else false
- bool check(const char *word)
- {
- unsigned int mav = hash(word);
- node *trav = table[mav];
- while (strcasecmp(trav->word, word) != 0)
- {
- trav = trav->next;
- }
- if (strcasecmp(trav->word, word) == 0)
- {
- return true;
- }
- return false;
- }
- // Hashes word to a number
- unsigned int hash(const char *word)
- {
- // TODO: Improve this hash function
- return toupper(word[0]) - 'A'; // first draft. just make it from letter A to letter Z (i.e 26 buckets). more buckets means faster time, but i'll focus on completion first
- }
- // Loads dictionary into memory, returning true if successful, else false
- bool load(const char *dictionary)
- {
- int swag = 0;
- FILE *ptrone = fopen(dictionary, "r");
- if (ptrone == NULL)
- {
- return false;
- }
- char buffer[LENGTH + 1];
- while (fscanf(ptrone, "%s", buffer) != EOF)
- {
- node *new = malloc(sizeof(node));
- if (new == NULL)
- {
- return false;
- }
- strcpy(new->word, buffer);
- counter = hash(new->word);
- if (swag == 0)
- {
- new->next = NULL;
- table[counter] = new;
- swag++;
- word_count++;
- }
- else
- {
- new->next = table[counter];
- table[counter] = new;
- word_count++;
- }
- }
- fclose(ptrone);
- return true;
- }
- // Returns number of words in dictionary if loaded, else 0 if not yet loaded
- unsigned int size(void)
- {
- if (word_count > 0)
- {
- return word_count;
- }
- else
- {
- return 0;
- }
- }
- // Unloads dictionary from memory, returning true if successful, else false
- bool unload(void)
- {
- for (int x = 0; x < 26; x++)
- {
- node *trav = table[x];
- while (trav != NULL)
- {
- table[x] = trav->next;
- free(trav);
- trav = table[x];
- }
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment