-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashtable_search.cpp
130 lines (119 loc) · 2.48 KB
/
hashtable_search.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Statistic{
int mem;
int cmpnum;
};
Statistic global_stats;
struct Node{
Node* ptr = NULL;
char* str = NULL;
};
void* bupt_malloc(size_t size){
if (size <= 0) {
return NULL;
}
global_stats.mem += size;
return malloc(size);
}
int byte_cmp(char a, char b)
{
global_stats.cmpnum++;
return a - b;
}
int main(){
Node* hashTable[4999];
for (int i = 0; i < 4999; i++){
hashTable[i] = (Node*)bupt_malloc(sizeof(Node));
hashTable[i]->ptr = NULL;
hashTable[i]->str = NULL;
}
FILE *fp;
if ((fp = fopen("./patterns-127w.txt", "r")) == NULL){
printf("error!");
return -1;
}
while (!feof(fp)){
char strLine[100] = { '\0' };
fgets(strLine, 1024, fp);
//将字符串转为int
int i = 0;
unsigned long long str2int = 0;
while (strLine[i] != '\n'&&strLine[i] != '\0'){
str2int = str2int * 131 + (int)(strLine[i]);
i++;
}
int index = str2int % 4999;
Node* position = hashTable[index];
while (position->ptr){
position = position->ptr;
}
Node* node = (Node*)bupt_malloc(sizeof(Node));
node->ptr = NULL;
node->str = NULL;
node->str = (char*)bupt_malloc(i+1);
for (int j = 0; j < i; j++){
node->str[j] = strLine[j];
}
node->str[i] = '\0';
position->ptr = node;
}
fclose(fp);
int wordsNum = 0;
int wordsSuccess = 0;
FILE * fp1;
if ((fp1 = fopen("./words-98w.txt", "r")) == NULL) //判断文件是否存在及可读
{
printf("error!");
return -1;
}
while (!feof(fp1)){
wordsNum++;
char strLine[100] = { '\0' };
fgets(strLine, 1024, fp1);
//将字符串转为int
int i = 0;
unsigned long long str2int = 0;
while (strLine[i] != '\n'&&strLine[i] != '\0'){
str2int = str2int * 131 + (int)(strLine[i]);
i++;
}
if (strLine[i] == '\n')
strLine[i] = '\0';
int index = str2int % 4999;
if (!hashTable[index]->ptr){
continue;;
}
else{
Node* pos = hashTable[index]->ptr;
while (pos){
int flag = 0;
if (strlen(strLine) == strlen(pos->str)){
for (flag = 0; flag < i; flag++){
if (byte_cmp(strLine[flag], *((pos->str) + flag))){
pos = pos->ptr;
break;
}
}
if (flag == i){
printf("%s yes\n", strLine);
wordsSuccess++;
break;
}
}
else{
pos = pos->ptr;
}
}
}
}
fclose(fp1);//关闭文件
printf("%d KB\n", global_stats.mem / 1000);
printf("%d 次\n", global_stats.cmpnum);
printf("words num:%d\n", wordsNum);
printf("words sucdess:%d\n", wordsSuccess);
cin.get();
return 0;
}