【发布时间】:2017-04-09 15:52:04
【问题描述】:
我被分配到这个实验室,我需要在其中创建一个散列函数,并计算在散列多达 30000 个元素的文件时发生的冲突次数。到目前为止,这是我的代码
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
long hashcode(string s){
long seed = 31;
long hash = 0;
for(int i = 0; i < s.length(); i++){
hash = (hash * seed) + s[i];
}
return hash % 10007;
};
int main(int argc, char* argv[]){
int count = 0;
int collisions = 0;
fstream input(argv[1]);
string x;
int array[30000];
//File stream
while(!input.eof()){
input>>x;
array[count] = hashcode(x);
count++;
for(int i = 0; i<count; i++){
if(array[i]==hashcode(x)){
collisions++;
}
}
}
cout<<"Total Input is " <<count-1<<endl;
cout<<"Collision # is "<<collisions<<endl;
}
我只是不确定如何计算碰撞次数。我尝试将每个散列值存储到一个数组中,然后搜索该数组,但是当只有 10000 个元素时,它会导致大约 12000 次冲突。任何关于如何计算冲突或者即使我的哈希函数可以使用改进的建议,都将不胜感激。谢谢。
【问题讨论】:
-
@chris 这是我的教授为我们预编的代码
-
请参阅stackoverflow.com/questions/8317508/hash-function-for-a-string 了解字符串的哈希函数。通常使用散列来索引散列表。所以你的逻辑有点奇怪。
-
@RichardChambers 他的帖子是我用来构建哈希函数的帖子之一,我的教授不希望将它们放入哈希表中,他只想将它们散列并计算碰撞次数跨度>
-
这并不能改变它不可靠的事实。如果输入失败,则无限循环。还要考虑案例where the input ends with whitespace。如您所见,这也会导致不良行为。