Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * dictionary.c
- *
- * Computer Science 50
- * Problem Set 5
- *
- * Implements a dictionary's functionality.
- */
- #include <stdbool.h>
- #include <stdlib.h>
- #include <math.h>
- #include <stdio.h>
- #include <string.h>
- #include <ctype.h>
- #include "dictionary.h"
- // linked list for words
- typedef struct node
- {
- char word[46];
- struct node* next;
- }
- node;
- node* hashtable[19683];
- // numbers of words loaded from dictionary
- int dic_num = 0;
- /**
- * Returns true if word is in dictionary else false.
- */
- bool check(const char* word)
- {
- char l_word[46];
- double num = 0;
- int idx = 0;
- for(int i = 0; i < 46; i++)
- {
- if(word[i] == '\0')
- {
- l_word[i] = '\0';
- break;
- }
- else
- {
- if(isalpha(word[i]) != 0 || word[i] == 39)
- l_word[i] = tolower(word[i]);
- }
- }
- for(int i = 0; i < 4; i++)
- {
- if(l_word[i] == '\0')
- break;
- else
- num += pow (27.0, (4.0 - i - 1))*(1 + l_word[i] - 'a');
- }
- idx = (int)num % 19683;
- node* n_ptr;
- for(n_ptr = hashtable[idx]; n_ptr != NULL; n_ptr = n_ptr->next)
- {
- if(strcmp(l_word, n_ptr->word) == 0)
- return true;
- }
- return false;
- }
- /**
- * Loads dictionary into memory. Returns true if successful else false.
- */
- bool load(const char* dictionary)
- {
- // initialize hashtable
- for(int i = 0; i < 19683; i++)
- hashtable[i] = NULL;
- // file pointer to dictionary
- FILE *fptr;
- // node pointer
- node *n;
- fptr = fopen(dictionary,"r");
- while(fgetc(fptr) != EOF)
- {
- node* new_node = malloc(sizeof(node));
- new_node->next = NULL;
- fscanf(fptr, "%s", new_node->word);
- double num = 0;
- for(int i = 0; i < 4; i++)
- {
- if(new_node->word[i] == '\0')
- break;
- else
- num += pow (27.0, (4.0 - i - 1))*(1 + new_node->word[i] - 'a');
- }
- int index = (int)num % 19683;
- if (hashtable[index] == NULL)
- {
- hashtable[index] = new_node;
- dic_num++;
- }
- else
- {
- // find end of linked list
- for(n = hashtable[index]; n != NULL; n = n-> next)
- {
- if(n -> next == NULL)
- {
- n->next = new_node;
- dic_num++;
- break;
- }
- }
- }
- }
- return true;
- }
- /**
- * Returns number of words in dictionary if loaded else 0 if not yet loaded.
- */
- unsigned int size(void)
- {
- if(dic_num == 0)
- return 0;
- else
- return dic_num;
- }
- /**
- * Unloads dictionary from memory. Returns true if successful else false.
- */
- bool unload(void)
- {
- for(int i = 0; i < 19683; 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