как сделать так, чтобы функция сравнения слов моего слова эффективно работала в c - PullRequest
0 голосов
/ 04 мая 2020

Я в настоящее время нахожусь на pset5 курса cs50, и цель состоит в том, чтобы написать функции, которые будут эффективно загружать словарь в память, функция ha sh и ha sh слова в таблицу ha sh , проверьте слова в данном тексте и верните true, если они внутри, и false, если нет. Они должны быть нечувствительны к регистру.

Теперь с моим кодом я хорошо справился с функциями load, ha sh, size и unload. Мне известно об утечке памяти, но я включу go после проверки. Однако я борюсь с функцией проверки, поэтому ниже приведен словарь. c

// Implements a dictionary's functionality
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <stdbool.h>

#include "dictionary.h"
//for the universal hash function
#define BASE 256

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

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

// Hash table
node *table[N];
int word_count = 0;

// Returns true if word is in dictionary else false
//Require a search funtion
bool check(const char *word)
{
    int hashIndex = hash(word);
    for (node *tmp = table[hashIndex]; tmp != NULL; tmp = tmp->next)
    {

        if (strcasecmp(word, tmp->word) == 0)
        {
            return true;
        }
    }
    return false;
}

// Hashes word to a number
// the dividing hash function is one I cited from the yale.edu page http://www.cs.yale.edu/homes/aspnes/pinewiki/C(2f)HashTables.html having worked with.
unsigned int hash(const char *word)
{
    unsigned long m = 11;
    unsigned long h;
    unsigned const char *us;
    //ensure element value is >= 0 
    us = (unsigned const char *) word;

    h = 0;
    while(*us != '\0') 
    {
        h = (h * BASE + *us) % m;
        us++;
    } 
    return (h % N);
}

// Loads dictionary into memory, returning true if successful else false
//Bring the used sictionary to menu asap
bool load(const char *dictionary)
{

    // Open file and check file 
    FILE *file = fopen(dictionary, "r");
    if (!file)
    {
        return false;
    }


    //array declaration for fscanf to read into
    char word[LENGTH + 1];
    while (fscanf(file, "%s", word) == 1)
    {
        //Create node n = new node
        node *n = malloc(sizeof(node));
        if (n == NULL)
        {
            printf("No memory for node\n");
            fclose(file);
            return false;

        }

        strcpy(n->word, word);

        //Hash the word
        int hashDigit = hash(word);
        //Insert into the beginning of the list
        if (table[hashDigit] == NULL)
        {
            table[hashDigit] = n;
            n->next = NULL;
        }
        else
        {
            n->next = table[hashDigit];
            table[hashDigit] = n;
        }
        word_count++;
    }
    return true;
}

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

    return word_count;
}

// Unloads dictionary from memory, returning true if successful else false
//free the dictionary from memory asap
bool unload(void)
{
    //Loop to run through array
    for (int i = 0; i < N; i++)
    {
        //to target linked list
        if (table[i] != NULL)
        {
            node *tmp = table[i]->next;
            free(table[i]);
            table[i] = tmp;
        }

    }
    return true;
}

Когда я запускаю его через функцию cs50 check50, он дает мне следующее:

:( проверка орфографии не зависит от регистра "MISSPELLED WOR ...", а не "MISSPELLED WOR ..." Журнал работает ./speller case / dict case / text ... проверка на вывод "MISSPELLED WORDS \ n \ n \ nWORDS MISSPELLED: 0 \ nWORDS IN DICTIONARY: 1 \ nWORDS IN TEXT: 8 \ n "...

Ожидаемый результат: НЕПРАВИЛЬНЫЕ СЛОВА

WORDS MISSPELLED: 0 СЛОВА В СЛОВАРЬ: 1 СЛОВА В ТЕКСТЕ:
8 Фактический результат: НЕПРАВИЛЬНЫЕ СЛОВА

foO fOo Foo FOO FoO FOO FOO

СЛОВА ЗАПИСАНЫ: 7 СЛОВ В СЛОВАРЬЕ: 1 СЛОВА В ТЕКСТЕ:
8

:( обрабатывает большинство основных c слов, ожидаемых должным образом «MISSPELLED WOR ...», а не «MISSPELLED WOR ...» Журнал запущен ./speller basic / dict basic / text ... проверка вывода "MISSPELLED СЛОВА \ n \ n \ nWORDS MISSPELLED: 0 \ nWORDS В СЛОВАРЕ: 8 \ nWORDS IN TEXT: 9 \ n "...

E ожидаемый результат: ЗАПИСАННЫЕ СЛОВА

СЛОВА ЗАПИСАННЫЕ: 0 СЛОВ В СЛОВАРЬЕ: 8 СЛОВ В ТЕКСТЕ:
9 Фактический результат: НЕПРАВИЛЬНЫЕ СЛОВА

СЛОВ ЗАПИСАНО: 1 СЛОВА В СЛОВАРЬЕ: 8 СЛОВ В ТЕКСТЕ:
9

И утечка памяти, на которой, как я уже говорил, я остановлюсь позже. Мой первый вопрос здесь состоит в том, как я могу позволить ему принимать базовые c слова, такие как «the» или «a» без жесткого кодирования, или это проблема неправильной проверки регистра слов без учета регистра? и во-вторых, что я делаю не так с проверкой регистра слов без учета регистра.

Я не могу понять, куда это go, и у меня возникло ощущение, что я неправильно использую функцию strcasecmp или неправильно перебираю таблицу ha sh.

1 Ответ

0 голосов
/ 04 мая 2020

Это if (strcasecmp(word, tmp->word) == 0) не единственное место, в котором значение слова имеет значение. А как насчет hash? Необходимо также учитывать регистр букв, так как, например, 'A' и 'a' будут иметь sh для различных значений.

...