joseleeph

Untitled

Nov 21st, 2020
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. // Implements a dictionary's functionality
  2. #include <stdio.h>
  3. #include <strings.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6. #include <stdbool.h>
  7. #include <cs50.h>
  8. #include "dictionary.h"
  9. #include <ctype.h>
  10.  
  11. // Represents a node in a hash table
  12. typedef struct node
  13. {
  14. char word[LENGTH + 1];
  15.  
  16. struct node *next;
  17. }
  18. node;
  19.  
  20. //create a hash table, an array of hash values
  21. int N = 26;
  22. int count = 0;
  23.  
  24. //node *table[26*3];
  25. node *table[26];
  26.  
  27. bool check(const char *word)
  28. {
  29. node *cursor = table[hash(word)];
  30. while (cursor != NULL)
  31. {
  32. if (strcasecmp(cursor->word,word) == 0)
  33. {
  34. return true;
  35. }
  36. cursor = cursor->next;
  37. }
  38. return false;
  39. }
  40.  
  41.  
  42. unsigned int hash(const char *word)
  43. {
  44. unsigned int val = 0;
  45. while(*word)// a pointer to the first char in a pointer to chars called word
  46. {
  47. val += tolower(*word++); //increment the pointer to the
  48. }
  49.  
  50. return val%N;
  51.  
  52.  
  53. //return 0;
  54. }
  55. bool load(const char *dictionary)
  56. {
  57. char word[LENGTH + 1]; // an array of characters
  58.  
  59. FILE *dictr = fopen(dictionary,"r"); // a pointer to a file in read mode
  60. if (dictr == NULL) // if there's nothing there
  61. {
  62. return false;
  63. }
  64. char buffer[LENGTH+1];
  65.  
  66.  
  67. while (fscanf(dictr,"%s", buffer) == 1)
  68. {
  69. node *myword = malloc(sizeof(node));
  70. if (myword == NULL)
  71. {
  72. return false;
  73. }
  74. strcpy(myword->word,buffer);
  75. int index = hash(buffer);
  76. myword->next = table[index];
  77. table[index] = myword;
  78. count++;
  79.  
  80. }
  81. return true;
  82. }
  83. unsigned int size(void)
  84. {
  85.  
  86. return count;
  87. }
  88.  
  89. bool unload(void)
  90. {
  91. while (cursor != NULL)
  92. {
  93. node *tmp = cursor;
  94. cursor = cursor->next;
  95. free(tmp);
  96. }
  97. return false;
  98. }
  99.  
Advertisement
Add Comment
Please, Sign In to add comment