0

i need help with my code . speller considers all words in text as misspelled . and i checked my code many times and i still don't know what's wrong .

#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>

#include "dictionary.h"

// Represents number of buckets in a hash table
#define N 2000

// create a variable to count the words in a dictionary
int word_counter = 0;

// Represents a node in a hash table
typedef struct node
{
    char word[LENGTH + 1];
    struct node *next;
}
node;

// Represents a hash table
node *hashtable[N];

// Hashes word to a number between 0 and 2000
unsigned int hash(const char *word)
{
    unsigned long hash = 5381;
    int c;

    while ((c = *word++))
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

    return hash;
}

load function :

bool load(const char *dictionary)
{
// Initialize hash table
for (int i = 0; i < N; i++)
{
    hashtable[i] = NULL;
}

// Open dictionary
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
    unload();
    return false;
}

// Buffer for a word
char word[LENGTH + 1];

// Insert words into hash table
while (fscanf(file, "%s", word) != EOF)
{
    // Add a null terminator to the end of the word
    word[strlen(word)] = '\0';


    int i = hash(word) % N;


    node *temp = malloc(sizeof(node));
    if(temp == NULL)
    {
        fclose(file);
        return false;
    }


    strcpy(temp -> word, word);

    if (hashtable[i] == NULL)
    {
        hashtable[i] = temp;
    }
    else
    {


        temp -> next = hashtable[i];


        hashtable[i] = temp;
    }


    word_counter++;
}

// Close dictionary
fclose(file);

// Indicate success
return true;
}

check function :

bool check(const char *word)
{
//Determine the length of the word
int len = strlen(word);


char copy[len+1];


for (int i = 0; i < len; i++)
{
    copy[i] = tolower(word[i]);
}


copy[len] = '\0';


int hashed = hash(copy) & N;


node *head = hashtable[hashed];



if(head != NULL)
{

    node *cursor = head;

    // Treverse the linked list
    while (cursor != NULL)
    {

        if (strcasecmp(cursor->word, word) != 0)
        {
            cursor = cursor->next;
        }
        else
        {
            return true;
        }
    }

}



return false;
}

thanks in advance .

5
  • Please add your hash function. Also, what is N? – Cliff B Mar 17 '19 at 23:46
  • i added the hash function . And N is the maximum size of the array – Mohamed Ayman Mar 18 '19 at 10:46
  • Is this int hashed = hash(copy) & N; a typo? Did you mean int hashed = hash(copy) % N;? – DinoCoderSaurus Mar 18 '19 at 11:06
  • oh !!! that was actually the problem . i don't know how i didn't notice that . thanks a lot – Mohamed Ayman Mar 18 '19 at 11:31
  • Glad it's solved. Can someone please post an answer? thanks. – Cliff B Mar 23 '19 at 1:43

You must log in to answer this question.

Browse other questions tagged .