Advertisement
Normantas

temp

Jul 19th, 2021
941
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.99 KB | None | 0 0
  1. // Implements a dictionary's functionality
  2.  
  3. #include <stdbool.h>
  4. #include <stdio.h>
  5. #include <strings.h>
  6. #include <ctype.h>
  7. #include <stdlib.h>
  8.  
  9. #include "dictionary.h"
  10.  
  11. // Represents a node in a hash table
  12. typedef struct node
  13. {
  14.     const char word[LENGTH+1];
  15.     struct node *next;
  16. }
  17. node;
  18.  
  19. // Dictionary size
  20. long dict_size = 0;
  21.  
  22. // Number of buckets in hash table
  23. const unsigned int N = 33;
  24.  
  25. // Hash table
  26. node *table[N] = {NULL};
  27.  
  28.  
  29. // Returns true if word is in dictionary, else false
  30. bool check(const char *word)
  31. {
  32.     node *curr = table[hash(word)];
  33.     while (curr != NULL)
  34.     {
  35.         if(strcasecmp(curr->word, word) == 0)
  36.             return true;
  37.  
  38.         // Goes to the next element
  39.         curr = curr->next;
  40.     }
  41.     return false;
  42. }
  43.  
  44. // Hashes word to a number
  45. unsigned int hash(const char *word)
  46. {
  47.     int c;
  48.     long hash = 0;
  49.     while ((c = *word++))
  50.     {
  51.         if (isupper(c))
  52.             c -= 65;
  53.         else if (islower(c))
  54.             c -= 97;
  55.         hash += c;
  56.     }
  57.  
  58.  
  59.     return hash % N;
  60. }
  61.  
  62. // Loads dictionary into memory, returning true if successful, else false
  63. bool load(const char *dictionary)
  64. {
  65.     FILE *file = fopen(dictionary, "r");
  66.     char *word;
  67.     while(fscanf(file, "%45s", word) == 1)
  68.     {
  69.         node *head = table[hash(word)];
  70.         node *child = malloc(sizeof (node));
  71.         child->next = head;
  72.         child->word = word;
  73.         table[hash(word)] = child;
  74.         dict_size++;
  75.     }
  76.     return true;
  77. }
  78.  
  79. // Returns number of words in dictionary if loaded, else 0 if not yet loaded
  80. unsigned int size(void)
  81. {
  82.     return dict_size;
  83. }
  84.  
  85. void unload_node(node *node)
  86. {
  87.     if(node->next != NULL)
  88.         unload_node(node->next);
  89.     free(node);
  90.     dict_size--;
  91.     return;
  92. }
  93.  
  94. // Unloads dictionary from memory, returning true if successful, else false
  95. bool unload(void)
  96. {
  97.     return true;
  98.     for(int i = 0; i < N; i++)
  99.     {
  100.         unload_node(table[i]);
  101.     }
  102.     return true;
  103. }
  104.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement