-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathE2.c
More file actions
122 lines (110 loc) · 2.66 KB
/
Copy pathE2.c
File metadata and controls
122 lines (110 loc) · 2.66 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BUCKETS 1000
#define MULTIPLIER 31
#define MAX_LEN 100
//Khởi tạo struct
struct wordrec
{
char* word;
unsigned long count;
struct wordrec* next;
};
//Cấp bộ nhớ cho node mới của wordrec
struct wordrec* walloc(const char* str)
{
struct wordrec* p=(struct wordrec*)malloc(sizeof(struct wordrec));
if(p!=NULL)
{
p->count=0;
p->word=strdup(str); //Tạo ra chuỗi copy.
p->next=NULL;
}
return p;
}
//Khởi tạo hash bucket.
struct wordrec* table[MAX_BUCKETS];
//Tạo ra chuỗi hash cho ký tự.
unsigned long hashstring(const char* str)
{
unsigned long hash=0;
while(*str)
{
hash=hash*MULTIPLIER+*str;
str++;
}
return hash%MAX_BUCKETS;
}
//Hàm để tính chuỗi hash, vào bucket của chuỗi hash và tìm bằng strcmp,
//trả lại pointer nếu tìm thấy từ đó. Nếu không tìm thấy
//sẽ tạo ra một node mới và đẩy lên đầu hash index.
struct wordrec* lookup(const char* str, int create)
{
unsigned long hash=hashstring(str);
struct wordrec* wp=table[hash];
struct wordrec* curr=NULL;
for(curr=wp; curr!=NULL; curr=curr->next)
if(strcmp(curr->word, str)==0) /* found */
{
return curr;
}
if(create)
{
curr=(struct wordrec*)malloc(sizeof(struct wordrec));
curr->word=strdup(str);
curr->count=0;
curr->next=table[hash];
table[hash]=curr;
}
return curr;
}
//Hàm giải phóng bộ nhớ đã cấp
void cleartable()
{
struct wordrec* wp=NULL, *p=NULL;
int i=0;
for(i=0; i<MAX_BUCKETS; i++)
{
wp=table[i];
while(wp)
{
p=wp;
wp=wp->next;
free(p->word);
free(p);
}
}
}
//Hàm main
int main(int argc, char* argv[])
{
FILE* fp=fopen("book.txt", "r"); //Đọc dữ liệu từ file book.txt
char word[1024];
struct wordrec* wp=NULL;
int i=0;
//Bắt table bắt đầu với dữ liệu NULL
memset(table, 0, sizeof(table));
//Đọc từ đầu vào
while(1)
{
if(fscanf(fp, "%s", word)!=1)
break;
wp=lookup(word, 1); //Tìm và tạo nếu không tồn tại
wp->count++;
}
fclose(fp);
//Hàm in ra tất cả các từ mà có tần xuất > 1000
for(i=0; i<MAX_BUCKETS; i++)
{
for(wp=table[i]; wp!=NULL; wp=wp->next)
{
if(wp->count>1000)
{
printf("%s-->%ld\n", wp->word, wp->count);
}
}
}
cleartable();
return 0;
}