0

my load function seems to only load two words and all words are coming back misspelled. I don't know if the problem is with my load function or the hash function. I've gone over the load function multiple times and I think it's right. I don't totally understand how the hash function is working so I suspect that the problem, though I've tried a several variations from other assignments and none seems to work. Many thanks!

bool check(const char *word)
{

    key = hash(word);

    if (table[key] == NULL)
    {
        return false;
    }

    node *cursor = table[key];

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


bool load(const char *dictionary)
{
    // open dictionary file
    FILE *file = fopen(dictionary, "r");

    if (file == NULL)
    {
       return 1;
    }

    // initialize table to NULL values
    for (int i = 0; i < N; i++)
    {
        table[i] = NULL;
    }

    // create array for words
    char word[LENGTH + 1];

    // scan each word from dictionary
    while (fscanf(file, "%s", word) != EOF)
    {
        // allocate memory for node and check for NULL
        node *n = malloc(sizeof(node));

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

        // copy word to node
        strcpy(n->word, word);
        n->next = NULL;

        // hash word with hash function to get index of table
        key = hash(word);

        // if no element at that location, add the node
        if (table[key] == NULL)
        {
            table[key] = n;
        }
        // if other elements at that location, add node at end
        else
        {
            node *tmp = malloc(sizeof(node));
            tmp = table[key];

            while (tmp->next != NULL)
            {
                tmp = tmp->next;
            }
            tmp->next = n;
        }
        word_count++;
    }

    fclose(file);

    return true;
}

This is the last hash function I tried


unsigned int hash(const char *word)
{

    unsigned long hash = 5381;
    int c;
    while ((c = toupper(*word++)))
    {
        hash = ((hash << 5) + hash) + c;
    }
    return hash % N;

}
2
  • There's no way to effectively answer the misspelling issue without seeing the check code. Can you please add it? – Cliff B Oct 16 '20 at 4:00
  • Added it. Thanks!! – David Oct 17 '20 at 2:54

You must log in to answer this question.

Browse other questions tagged .