joseleeph

Untitled

Nov 21st, 2020
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 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. const int N = 26;
  22. int count = 0;
  23.  
  24.  
  25. node *table[N];
  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. // Hashes word to a number
  43. unsigned int hash(const char *word)// to hash a-z 0-26, maybe use ascii value and subtract?
  44. {
  45. unsigned int val = 0;
  46. while(*word)// a pointer to the first char in a pointer to chars called word
  47. {
  48. val += tolower(*word++); //increment the pointer to the
  49. }
  50.  
  51. return val%N;
  52. }
  53. bool load(const char *dictionary)
  54. {
  55. char word[LENGTH + 1]; // an array of characters
  56. //int count = 0;
  57. FILE *dictr = fopen(dictionary,"r"); // a pointer to a file in read mode
  58. if (dictr == NULL) // if there's nothing there
  59. {
  60. return false;
  61. }
  62. char buffer[LENGTH+1]; // create an array
  63.  
  64. while (fscanf(dictr,"%s", buffer) == 1)
  65. {
  66.  
  67. node *myword = malloc(sizeof(node));
  68. if (myword == NULL)
  69. {
  70. return false;
  71. }
  72.  
  73. strcpy(myword->word,buffer);
  74. int index = hash(buffer);
  75. myword->next = table[index];
  76. table[index] = myword;
  77. count++;
  78.  
  79. }
  80. return true;
  81. }
  82.  
  83. // Returns number of words in dictionary if loaded else 0 if not yet loaded
  84. unsigned int size(void)
  85. {
  86. return count;
  87. }
  88.  
  89. bool unload(void)
  90. {
  91. node *cursor = table[hash(0)];
  92. while (cursor != NULL)
  93. {
  94. node *tmp = cursor;
  95. cursor = cursor->next;
  96. free(tmp);
  97. }
  98. return false;
  99. }
  100.  
Advertisement
Add Comment
Please, Sign In to add comment