Advertisement
kabman7

dictionary.c

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