Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ctype.h>
- #include <stdbool.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <strings.h>
- #include "dictionary.h"
- // Represents number of buckets in a hash table
- #define N 26
- // Represents a node in a hash table
- typedef struct node
- {
- char word[LENGTH + 1];
- struct node *next;
- }
- node;
- // Represents a hash table
- node *hashtable[N];
- // Keeps track of the words that we loaded
- int words = 0;
- // Creates the head of the hashtable pointer
- node *head;
- // Hashes word to a number between 0 and 25, inclusive, based on its first letter
- unsigned int hash(const char *word)
- {
- return tolower(word[0]) - 'a';
- }
- // Loads dictionary into memory, returning true if successful else false
- bool load (const char *dictionary)
- {
- // Initialize hash table
- for (int i = 0; i < N; i++)
- {
- hashtable[i] = NULL;
- }
- // Open dictionary
- FILE *file = fopen(dictionary, "r");
- if (file == NULL)
- {
- unload();
- return false;
- }
- // Buffer for a word
- char word[LENGTH + 1];
- int index;
- // Insert words into hash table
- while (fscanf(file, "%s", word) != EOF)
- {
- // Saves the hash of dictionary words into a variable of index
- index = hash(word);
- // Create nodes with a numbered name based on how many times while has ran
- node *newNode = malloc(sizeof(node));
- if (newNode == NULL)
- {
- unload();
- return false;
- }
- // Copies word from dictionary into the new node created
- strcpy(newNode->word, word);
- // first one
- if(newNode == NULL)
- {
- head = newNode;
- hashtable[index] = newNode;
- }
- else
- {
- newNode->next = hashtable[index];
- hashtable[index] = newNode;
- }
- // Increment after every word added
- words++;
- }
- printf("Counter: %i\n", words);
- // Close dictionary
- fclose(file);
- // Indicate success
- return true;
- }
- // Returns number of words in dictionary if loaded else 0 if not yet loaded
- unsigned int size(void)
- {
- if (words > 0)
- {
- return words;
- }
- else
- return 0;
- }
- // Returns true if word is in dictionary else false
- bool check(const char *word)
- {
- int index = hash(word);
- if (strcasecmp(hashtable[index]->word, word) == 0)
- {
- return true;
- }
- return false;
- }
- // Unloads dictionary from memory, returning true if successful else false
- bool unload(void)
- {
- // TODO
- node *trav = head;
- while(trav != NULL)
- {
- node *tmp = trav;
- trav = trav->next;
- free(tmp);
- }
- if(head == NULL)
- {
- return true;
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement