Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Implements a dictionary's functionality
- // This is just an inefficient way to hash a table
- // I want to try hashing myself before using popular hash algorithms
- #include <stdbool.h>
- #include <ctype.h>
- #include "dictionary.h"
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.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 = 26;
- unsigned int total;
- node *table[N];
- // Returns true if word is in dictionary, else false
- bool check(const char *word)
- {
- int l = strlen(word)+1;
- char p[l];
- strcpy(p,word);
- //One liner for-loop to lowercasing p
- //tolower cause p to point to new address
- for (int i = 0; i < l; i++) p[i] = tolower(p[i]);
- node *temp;
- int i = hash(p);
- temp = table[i];
- //scanning index node and check if input word is correct
- while(temp)
- {
- if(!strcmp(temp->word,p))
- {
- return true;
- }
- temp = temp->next;
- }
- return false;
- }
- // Hashes word to a number
- unsigned int hash(const char *word)
- {
- //Hash alphabetically.
- return ((unsigned int)word[0] % 97);
- }
- // Loads dictionary into memory, returning true if successful
- bool load(const char *dictionary)
- {
- FILE *fp = fopen(dictionary,"r");
- //LENGTH = 45 defined in dictionary.h
- //sizeof(char) equal to 1, so there's no need to put it in malloc
- char *word = malloc(LENGTH + 1);
- //[\n] regex use to read 1 word at a time.
- while(fscanf(fp,"%s[\n]",word) != EOF)
- {
- node *n = malloc(sizeof(node));
- if(n == NULL)
- {
- printf("error: Out of memory");
- return false;
- }
- else if(word[0] == '\0')
- {
- free(n);
- return false;
- }
- size();
- int index = hash(word);
- strcpy(n->word,word);
- //If there's an existing node in current index, link it. Else initialize it.
- n->next = NULL;
- node *temp = table[index];
- if(!temp)
- {
- table[index] = n;
- continue;
- }
- for(;temp->next;) temp = temp->next;
- temp->next = n;
- }
- --total;
- free(word);
- fclose(fp);
- return true;
- }
- // Returns number of words in dictionary if loaded, else return 0.
- unsigned int size(void)
- {
- total++;
- return total;
- }
- // Unloads dictionary from memory
- bool unload(void)
- {
- // TODO
- for(int i = 0; i < N; i++)
- {
- while(table[i])
- {
- node *temp = table[i]->next;
- free(table[i]);
- table[i] = temp;
- }
- }
- return true;
- }
Add Comment
Please, Sign In to add comment