Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Implements a dictionary's functionality
- #include <cs50.h>
- #include <stdlib.h>
- #include <string.h>
- #include <strings.h>
- #include <ctype.h>
- #include <stdbool.h>
- #include <stdio.h>
- #include "dictionary.h"
- #define Q 26 // rep number of buckets or lists in a hash table
- int r = 0;
- // Represents a node in a hash table
- typedef struct node
- {
- char word[LENGTH + 1];
- struct node *next;
- }
- node;
- // Represents a hash table // now double array
- node *hashtable[Q];
- // 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 < Q; i++)
- {
- // init
- // hashtable[i] = NULL;
- // malloc a node for every word scan
- hashtable[i] = malloc(sizeof(node));
- // check if malloc is successful
- if (hashtable[i] == NULL)
- {
- unload();
- return false;
- }
- }
- // Open dictionary
- FILE *file = fopen(dictionary, "r");
- if (file == NULL)
- {
- unload();
- return false;
- }
- // Buffer for a word
- char word[LENGTH + 1];
- // Insert words into hash table
- while (fscanf(file, "%s", word) && !feof(file)) // !EOF
- {
- // TODO
- r++; // counting no. of words
- // hash
- int y = hash(word);
- // malloc a node for every word scan
- /*hashtable[y] = malloc(sizeof(node)); // for dictionary file
- // check if malloc is successful
- if (hashtable[y] == NULL)
- {
- unload();
- return false;
- }*/
- strcpy(hashtable[y]->word, word);
- node *head = hashtable[y];
- hashtable[y]->next = head;
- head = hashtable[y];
- }
- // 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)
- {
- // TODO
- return r;
- }
- // Returns true if word is in dictionary else false
- bool check(const char *word)
- {
- // TODO
- int y = hash(word); // hash has to be deterministic
- // compare
- if (strcasecmp(hashtable[y]->word, word) == 0)
- {
- return true;
- }
- return false;
- }
- // Unloads dictionary from memory, returning true if successful else false
- bool unload(void)
- {
- // TODO
- for (int i = 0; i < Q; i++)
- {
- free(hashtable[i]); //
- if (i == Q - 1) // if end
- {
- return true;
- }
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement