从 .txt 文件创建一个哈希表并计算冲突

问题描述

我有关于哈希表的作业。老师介绍以及我在下面卡在哪里:

将 1000 个密码列表插入具有适当散列函数的散列表中。如果冲突次数不超过 200 次会更好。使用哈希表搜索 1000 个密码列表中的密码,并报告该搜索的冲突计数。

#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define tableSize  1200
// Create file pointer data.txt
FILE *fp;

//Struct
typedef struct{
    
    char pw[30];
    
}list;

list passwords[1000];
list hashTable[tableSize];



// Clear Function
void clear(){
    for(int i = 0; i <= tableSize; i++){
        
        strcpy(hashTable[i].pw,"");
        
    }
}

// display
void display(){
    for(int i = 0; i < tableSize; i++){
        if(hashTable[i].pw == NULL){
            printf("Hash Table [%d] is empty\n",(i + 1));
        }
        else{
            printf("%s",hashTable[i].pw);
        } 
    }
}

// Insert
int insert(int l,int index){
    static int count = 0;
    if(hashTable[index].pw != NULL && index < 100){
        count++;
        return insert(l,index + 1);
    }
    else if(index == 100 && hashTable[index].pw != NULL){
        count++;
        return insert(l,0);
    }
    else if(hashTable[index].pw == NULL){
        
        strcpy(hashTable[index].pw,passwords[l].pw);
            
        
    }   
}



// F1
int hash1(){
    srand(time(0));
    int l = 0,index = 0,score;
    for(int i = 0; i <= tableSize; i++){
        l =  rand() % tableSize;
        insert(l,tableSize % 3);
    }   
    return score;
}




int main(){
    fp = fopen("1000.txt","r");
    char s[1000];
    const char *buffer;

    int i = 0;
    while(fgets(s,100,fp))
    {
        if(i < 100){
        

            buffer = strtok(NULL,"");
            strcpy(passwords[i].pw,buffer);
        
        }
        i++;
    }



    hash1();
    printf("Hash Function 1\n");
    display();


    return 0;
}

密码列表中有一堆不同类型的整数和字符串的密码。 .txt 文件的一部分是:

abc123
football
monkey
letmein
696969
shadow
master
666666
qwertyuiop
123321
mustang

我想我可以将所有这些都作为字符串获取,但是我无法打印表格以在搜索时检查并获取碰撞计数。此外,它只是 1 个主要功能中 4 个任务的一部分。所以如果我把它写成一个在 main() 中调用函数会更好。你能帮我吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)