Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /****************************************************************************
- * dictionary.c
- *
- * Computer Science 50
- * Problem Set 6
- *
- * Implements a dictionary's functionality.
- ***************************************************************************/
- #include <stdio.h>
- #include <stdbool.h>
- #include <stdlib.h>
- #include "dictionary.h"
- #include <ctype.h>
- #include <string.h>
- #define SIZE 26
- typedef struct node
- {
- char word[LENGTH + 1];
- struct node* next;
- }
- node;
- // Make a hash table
- node* hashtable[SIZE];
- char temp_word[LENGTH + 1];
- unsigned int word_ctr = 0;
- int table_pos(const char* word)
- {
- int table_pos = 0;
- int hash;
- for (int i = 0; word[i] != '\0'; i++)
- {
- // check if word is alpha
- if (isalpha(word[i]))
- {
- hash = word[i] - 'a';
- }
- else
- {
- hash = 26;
- }
- table_pos = hash % SIZE;
- }
- return table_pos;
- }
- /**
- * Returns true if word is in dictionary else false.
- */
- bool check(const char* word)
- {
- // TODO
- char new_word[LENGTH +1];
- for (int i = 0,n = strlen(word); i <= n; i++)
- {
- new_word[i] = word[i];
- new_word[i] = tolower(new_word[i]);
- }
- // determine the correct hash position
- int y = table_pos(new_word);
- // point the cursor to the first item in the list we identified
- node* cursor = hashtable[y];
- // search the linked list
- while (cursor != NULL)
- {
- // printf("%s,%s",cursor->word,new_word);
- if (strcmp(cursor->word,new_word) == 0)
- {
- return true;
- }
- else
- {
- cursor = cursor->next;
- }
- }
- return false;
- }
- /**
- * Loads dictionary into memory. Returns true if successful else false.
- */
- bool load(const char* dictionary)
- {
- // TODO
- // do some prep work
- FILE* inptr = fopen(dictionary,"r");
- if (inptr == NULL)
- {
- printf("Could not open %s.\n",dictionary);
- return 2;
- }
- //while there are words available
- while (fscanf(inptr,"%s\n",temp_word) != EOF)
- {
- node* new_node = malloc(sizeof(node));
- new_node->next = NULL;
- strcpy(new_node->word, temp_word);
- word_ctr++;
- int x = table_pos(new_node->word);
- // get it into that list
- new_node->next = hashtable[x];
- hashtable[x] = new_node;
- }
- //do some cleanup work
- fclose(inptr);
- return true;
- }
- /**
- * Returns number of words in dictionary if loaded else 0 if not yet loaded.
- */
- unsigned int size(void)
- {
- // TODO
- return word_ctr;
- }
- /**
- * Unloads dictionary from memory. Returns true if successful else false.
- */
- bool unload(void)
- {
- // TODO
- for (int i = 0; i < SIZE ; 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