Advertisement
hozongjun

Untitled

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