I am (still!!!) stuck. I have a number of problems. Above is what I get if I run the cat text through both functions. Load and check are labeled to show which is which.
- The first is that my hash function returns different indexes for the same word, using the same text. I am keeping the case the same for the hash.
- I cannot get
strcmp
to compare the lower case version of the word, even though I input it, and so returns a spelling error on capitals. I tried comparing the lowercase version of the word,arr
but this does not work either. So I always get an error on the letterA
of cat.txt.
While it might not be evident here, I have already done extensive debugging, yet I am still stuck.
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
node *hash_table[HASHTABLE_SIZE] = {NULL};
CHECK
bool check(const char *word)
{
int len = strlen(word);
char arr[len+1];
// SET WORD TO LOWER - not being used here
for(int i = 0; i < strlen(word);i++)
{
arr[i] = tolower(word[i]);
}
arr[len] = '\0';
int hash_index = hashValue(word);
//set head to first node in bucket/array - node
node *head = hash_table[hash_index];
node *cursor = head;
while(cursor != NULL)
{
//use original case of the word
if(strcmp(word, cursor->word) == 0)
{
// puts("equal");
return true;
}
cursor = head->next;
head = cursor;
}
// printf("misspelled %s\n", arr);
return false;
}
LOAD
bool load(const char *dictionary)
{
FILE *inptr = fopen(dictionary, "r");
char temp[LENGTH+1];
while(fscanf(inptr,"%s",temp) != EOF)
{
node *mem = malloc(sizeof(node));
if(mem == NULL)
{
return 1;
}
// copy line into node's word
strcpy(mem->word, temp);
// hash it
int hash_index = hashValue(temp);
// if null, head is empty
if(hash_table[hash_index] == NULL)
{
// insert at head of linked list
// same as head = mem
hash_table[hash_index] = mem;
// make next null
mem->next = NULL;
}
else
{
// set next to current head
mem->next = hash_table[hash_index];
// reassign head to new node
hash_table[hash_index] = mem;
}
}
fclose(inptr);
// puts("made it to end");
return true;
}
HASH FUNCTION via reddit
int hashValue(const char *word)
{
unsigned int hash = 0;
for (int i=0, n=strlen(word); i<n; i++) {
hash = (hash << 2) ^ word[i];
}
// returns a number
return hash % HASHTABLE_SIZE;
}
UNLOAD
bool unload(void)
{
for(int i = 0;i < HASHTABLE_SIZE; i++)
{
node *head = hash_table[i];
node *cursor = head;
if(cursor != NULL){
// set temp to cursor
node *temp = cursor;
// point cursor at next node
cursor = cursor-> next;
free(temp);
}
}
return true;
}