0

When I test my code...it counts most words as misspelled and only 1 or 2 words as being in dictionary..i presume the issue is in the check function...i do believe the load function works just fine as well as the hash function but please do point out any issues i might be overlooking.

This is the code: [i'm still not done with unload but that's an issue for another question]

// Number of buckets in hash table
const unsigned int N = 100;

int count = 0;

// Hash table
node *table[N];

// Returns true if word is in dictionary else false
bool check(const char *word)
{
    // TODO
    int x = hash(word);

    node *cursor = table[x];

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

// Hashes word to a number
/* A case-insensitive implementation of the djb2 hash function.
 * Adapted by Neel Mehta from
 * http://stackoverflow.com/questions/2571683/djb2-hash-function.
 */
unsigned int hash(const char *word)
 {
     unsigned long hash = 5381;

     for (const char* ptr = word; *ptr != '\0'; ptr++)
     {
         hash = ((hash << 5) + hash) + tolower(*ptr);
     }

     return hash % N;
 }

// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
    // TODO
    FILE *dic = fopen(dictionary, "r");

    if (dic == NULL)
    {
       return false;
    }

    node *n = NULL;
    char term[LENGTH + 1];

    while (fscanf(dic, "%s", term) != EOF)
    {
        n = malloc(sizeof(node));

        if (n == NULL)
        {
            return false;
        }

        strcpy(n->word, term);

        int x = hash(n->word);

        n->next = table[x];
        table[x] = n;

        count++;

        return true;
    }
    return false;
}

// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
    return count;
}

This is the Check50 result: https://submit.cs50.io/check50/47b1aa7357c64bbdd4437f8948639808a0d9915c

1

Let's look at the while loop in load:

while (fscanf(dic, "%s", term) != EOF)
{
    n = malloc(sizeof(node));

    if (n == NULL)
    {
        return false;
    }

    strcpy(n->word, term);

    int x = hash(n->word);

    n->next = table[x];
    table[x] = n;

    count++;

    return true;
}

How many times do you think this loop will run? What happens when the code hits return true; ????

Here's another clue. How many words in your dictionary???? ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .