-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercicio2c.c
272 lines (215 loc) · 7.24 KB
/
exercicio2c.c
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
// ========================================================================================================
//
// @file exercicio2c.c
// @authors Guilherme Mafra (N USP: 11272015), Luigi Quaglio (N USP: 11800563) and Maíra Canal (N USP: 11819403)
//
// ========================================================================================================
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <string.h>
#include <math.h>
// Definição das variaveis que controlam a medição de tempo
clock_t _ini, _fim;
// Definição do tipo booleano
typedef unsigned char bool;
#define TRUE 1
#define FALSE 0
// Definição do tipo string
typedef char * string;
#define MAX_STRING_LEN 20
// DESENVOLVIDA PELO GRUPO ================================================================================
typedef struct no {
char key[MAX_STRING_LEN];
struct no *proximo;
} No;
typedef struct {
unsigned B;
No **tabela;
} Hash;
// ========================================================================================================
unsigned converter(string s) {
unsigned h = 0;
for (int i = 0; s[i] != '\0'; i++)
h = h * 256 + s[i];
return h;
}
string* ler_strings(const char * arquivo, const int n)
{
FILE* f = fopen(arquivo, "r");
string* strings = (string *) malloc(sizeof(string) * n);
for (int i = 0; !feof(f); i++) {
strings[i] = (string) malloc(sizeof(char) * MAX_STRING_LEN);
fscanf(f, "%s\n", strings[i]);
}
fclose(f);
return strings;
}
void inicia_tempo()
{
srand(time(NULL));
_ini = clock();
}
double finaliza_tempo()
{
_fim = clock();
return ((double) (_fim - _ini)) / CLOCKS_PER_SEC;
}
unsigned h_div(unsigned x, unsigned B)
{
return x % B;
}
unsigned h_mul(unsigned x, unsigned B)
{
const double A = 0.6180;
return fmod(x * A, 1) * B;
}
// DESENVOLVIDA PELO GRUPO ================================================================================
/*
* @brief Aloca memória da tabela hash e preenche todos os enderecos com NULL.
*/
void criar_hash(Hash *hash, unsigned B)
{
hash->B = B;
hash->tabela = (No **) malloc(B * sizeof(No*));
for (int i = 0; i < B; i++)
hash->tabela[i] = NULL;
}
/*
* @brief Insere um novo nó na lista encadeada linear
*/
void inserir_node(No** raiz, string elemento)
{
No* novo_no = (No*) malloc(sizeof(No));
strcpy(novo_no->key, elemento);
novo_no->proximo = *raiz;
*raiz = novo_no;
}
/*
* @brief Busca de forma recursiva um nó em uma lista encadeada
* @return Retorna -1 caso o nó não seja encontrado e retorna 0 caso o nó seja encontrado
*/
int buscar_node(No *no, string elemento)
{
if (no == NULL)
return -1;
if (!strcmp(no->key, elemento))
return 0;
return buscar_node(no->proximo, elemento);
}
/*
* @brief Insere elemento na tabela hash utilizando a funcao hash (unsigned *funcao_hash). Além disso, também
* realiza o tratamento de colisões por meio da técnica de encadeamento em lista linear não ordenada.
* @return Retorna 0 se não houve colisão e retorna 1 caso tenha havido colisão
*/
int inserir_hash(Hash *hash, string elemento, unsigned (*funcao_hash)(unsigned, unsigned))
{
int colisao = 0;
unsigned key = converter(elemento);
unsigned pos = funcao_hash(key, hash->B);
if (!buscar_node(hash->tabela[pos], elemento))
return colisao;
if (hash->tabela[pos] == NULL) {
hash->tabela[pos] = (No *) malloc(sizeof(No));
hash->tabela[pos]->proximo = NULL;
} else colisao = 1;
inserir_node(&(hash->tabela[pos]), elemento);
return colisao;
}
/*
* @brief Busca um elemento na tabela hash utilizando a funcão hash (unsigned *funcao_hash). Conforme a funcão inserir_hash,
* é utilizado a técnica de encadeamento em lista linear não ordenada.
* @return Retorna -1 se o elemento não existir. Caso o elemento exista, retorna 0.
*/
int buscar_hash(Hash *hash, string elemento, unsigned (*funcao_hash)(unsigned, unsigned))
{
unsigned key = converter(elemento);
unsigned pos = funcao_hash(key, hash->B);
return buscar_node(hash->tabela[pos], elemento);
}
/*
* @brief Libera a memória alocada na tabela hash e nas listas encadeadas.
*/
void liberar_hash(Hash *hash)
{
for (int i = 0; i < hash->B; i++)
{
while (hash->tabela[i])
{
No* tmp = hash->tabela[i];
hash->tabela[i] = hash->tabela[i]->proximo;
free(tmp);
}
}
free(hash->tabela);
}
// ========================================================================================================
int main(int argc, char const *argv[])
{
const int N = 50000;
const int M = 70000;
const int B = 150001;
unsigned colisoes_h_div = 0;
unsigned colisoes_h_mul = 0;
unsigned encontrados_h_div = 0;
unsigned encontrados_h_mul = 0;
string* insercoes = ler_strings("strings_entrada.txt", N);
string* consultas = ler_strings("strings_busca.txt", M);
Hash hash;
// cria tabela hash com hash por divisão
criar_hash(&hash, B);
// inserção dos dados na tabela hash usando hash por divisão
inicia_tempo();
for (int i = 0; i < N; i++) {
// inserir insercoes[i] na tabela hash
if (inserir_hash(&hash, insercoes[i], &h_div))
colisoes_h_div++;
}
double tempo_insercao_h_div = finaliza_tempo();
// busca dos dados na tabela hash com hash por divisão
inicia_tempo();
for (int i = 0; i < M; i++) {
// buscar consultas[i] na tabela hash
if (buscar_hash(&hash, consultas[i], &h_div) != -1)
encontrados_h_div++;
}
double tempo_busca_h_div = finaliza_tempo();
// destroi tabela hash com hash por divisão
liberar_hash(&hash);
// cria tabela hash com hash por multiplicação
criar_hash(&hash, B);
// inserção dos dados na tabela hash com hash por multiplicação
inicia_tempo();
for (int i = 0; i < N; i++) {
// inserir insercoes[i] na tabela hash
if (inserir_hash(&hash, insercoes[i], &h_mul))
colisoes_h_mul++;
}
double tempo_insercao_h_mul = finaliza_tempo();
// busca dos dados na tabela hash com hash por multiplicação
inicia_tempo();
for (int i = 0; i < M; i++) {
// buscar consultas[i] na tabela hash
if (buscar_hash(&hash, consultas[i], &h_mul) != -1)
encontrados_h_mul++;
}
double tempo_busca_h_mul = finaliza_tempo();
// destroi tabela hash com hash por multiplicação
liberar_hash(&hash);
printf("Hash por Divisão\n");
printf("Colisões na inserção: %d\n", colisoes_h_div);
printf("Tempo de inserção : %fs\n", tempo_insercao_h_div);
printf("Tempo de busca : %fs\n", tempo_busca_h_div);
printf("Itens encontrados : %d\n", encontrados_h_div);
printf("\n");
printf("Hash por Multiplicação\n");
printf("Colisões na inserção: %d\n", colisoes_h_mul);
printf("Tempo de inserção : %fs\n", tempo_insercao_h_mul);
printf("Tempo de busca : %fs\n", tempo_busca_h_mul);
printf("Itens encontrados : %d\n", encontrados_h_mul);
// Desaloca memória previamente alocada
free(insercoes);
free(consultas);
return 0;
}