源代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int hashFunc(char *c, int size) {
int hashVal;
for(hashVal = 0; *c != '\0'; c++) {
hashVal = hashVal + *c;
}
return hashVal % size;
}
int main() {
int size;
char temp[60];
char **name;
int *entries;
char c;
int ctr=0;
int i,j;
int hashResult;
scanf("%d", &size);
FILE *file;
file = fopen("input.txt", "r");
name = (char**)malloc(sizeof(char*) * size);
for(i=0; i<size; i++) {
name[i] = (char*)malloc(sizeof(char) * size);
}
entries = (int*)malloc(sizeof(int) * size);
memset(&temp[0], 0, sizeof(temp));
if(file) {
while((c = getc(file)) != EOF) {
if(c == '\n' || ungetc(getc(file), file) == EOF) {
if(strlen(temp) > 0) {
printf("completed : %s\n", temp);
hashResult = hashFunc(temp, size);
entries[hashResult]++;
memset(&temp[0], 0, sizeof(temp));
ctr=0;
}
}
if(c != '\n') {
temp[ctr++] = c;
}
} // end of while
for(i=0; i<size; i++) printf("entries[%d]=%d\n", i, entries[i]);
fclose(file);
for(i=0; i<size; i++) free(name[i]);
free(name);
} else {
printf("no such file\n");
}
}
1st input.txt:
this is a
test file
for b4
a smll file but could
be effective
aaaaa
sdfghj
第二个input.txt(sdfghj之后只有一个空行:
this is a
test file
for b4
a smll file but could
be effective
aaaaa
sdfghj
* PLZ注意sdfghj在2ND INPUT.TXT之后有一条空白线
输出第一个input.txt:
10
completed : this is a
completed : test file
completed : for b4
completed : a smll file but could
completed : be effective
completed : aaaaa
completed : sdfgh
entries[0]=0
entries[1]=1
entries[2]=0
entries[3]=0
entries[4]=1
entries[5]=1
entries[6]=2
entries[7]=1
entries[8]=0
entries[9]=1
输出第二个input.txt:
10
completed : this is a
completed : test file
completed : for b4
completed : a smll file but could
completed : be effective
completed : aaaaa
completed : sdfghj
entries[0]=1
entries[1]=1
entries[2]=0
entries[3]=0
entries[4]=0
entries[5]=1
entries[6]=2
entries[7]=1
entries[8]=0
entries[9]=1
此程序计算哈希函数的冲突。
您好。我不明白为什么第1和第2个input.txt的输出(从条目[0]到条目[9])不同。
只有那些input.txt之间的区别在于,在第二个input.txt
之后,单词结束后有一个空白行,即sdfghj。如果你查看我的代码,我会阻止任何空行: if(strlen(temp)&gt; 0){
但输出(从条目[0]到条目[9])是不同的。如果我在单词之间留空行而不是input.txt的结尾,则输出相同。只在输入结尾处输入空白行.txt会产生不同的输出。
为什么会这样?