Advertisement
Guest User

Untitled

a guest
Aug 16th, 2020
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. // Implements a dictionary's functionality
  2.  
  3. #include <stdbool.h>
  4. #include <stdio.h>
  5. #include "dictionary.h"
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <strings.h>
  9. #include <ctype.h>
  10. // Represents a node in a hash table
  11. typedef struct node
  12. {
  13. char word[LENGTH + 1];
  14. struct node *next;
  15. }
  16. node;
  17.  
  18. // Number of buckets in hash table
  19. const unsigned int N = 55;
  20.  
  21. // Hash table
  22. node *table[N];
  23.  
  24. // Returns true if word is in dictionary else false
  25. bool check(const char *word)
  26. {
  27. int num = hash(word);
  28. node *cursor = malloc(sizeof(node));
  29. while (table[num] -> next != NULL)
  30. {
  31. cursor = table[num] -> next;
  32. if (strcasecmp(word, table[num] -> word) == 0)
  33. {
  34. return true;
  35. break;
  36. }
  37. else
  38. {
  39. table[num] = cursor;
  40. }
  41. }
  42.  
  43. return true;
  44. }
  45.  
  46. // Hashes word to a number
  47. unsigned int hash(const char *word)
  48. {
  49. unsigned int hash = 5381;
  50. int c;
  51.  
  52. while ((c = *word++))
  53. {
  54. hash = ((hash << 5) + hash) + tolower(c);
  55. }
  56. return hash % N;
  57.  
  58. }
  59.  
  60. // Loads dictionary into memory, returning true if successful else false
  61. bool load(const char *dictionary)
  62. {
  63. int size1 = 0;
  64. FILE *file = fopen (dictionary, "r");
  65. if(file == NULL) {
  66. printf("File could not be opened.\n");
  67. return false;
  68. }
  69. char word1[46];
  70. while(fscanf(file, "%s" ,word1) != EOF)
  71. {
  72. node *n = malloc(sizeof(node));
  73. if (n == NULL)
  74. {
  75. unload();
  76. return 1;
  77. }
  78. strcpy(n -> word, word1);
  79. n -> next = NULL;
  80. size1 = size(size1);
  81. int index = hash(word1);
  82. if (table[index] == NULL)
  83. {
  84. table[index] = n;
  85. }
  86. else
  87. {
  88. n -> next = table[index];
  89. table[index] = n;
  90. }
  91. }
  92. fclose(file);
  93. return true;
  94. }
  95.  
  96. // Returns number of words in dictionary if loaded else 0 if not yet loaded
  97. unsigned int size(int size1)
  98. {
  99.  
  100. return size1+1;
  101. }
  102.  
  103. // Unloads dictionary from memory, returning true if successful else false
  104. bool unload(void)
  105. {
  106. for (int i = 0; i < N; i++)
  107. {
  108. node *tmp = table[i];
  109. node *cursor = table[i];
  110. while(cursor -> next != NULL)
  111. {
  112.  
  113. cursor = cursor -> next;
  114. free(tmp);
  115. tmp = cursor;
  116. }
  117. }
  118. return true;
  119. }
  120.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement