-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash.c
executable file
·134 lines (98 loc) · 2.32 KB
/
hash.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
//Mihai Neacsu 331CA
//SO Tema 0
#include "hash.h"
#include <stdlib.h>
#include <assert.h>
Hash new_Hash(int length){
Hash newHash;
int i;
newHash = malloc(sizeof(struct hashmap));
newHash->length = length;
newHash->lists = calloc(length, sizeof(struct list *));
for (i = 0; i < length; ++i)
newHash->lists[i] = new_List();
return newHash;
}
void add_Hash(Hash H, const void *toAdd){
unsigned int value;
assert(H && toAdd);
value = hash((char *)toAdd, H->length);
append_List(H->lists[value], toAdd);
}
void remove_Hash(Hash H, const void *toRemove){
unsigned int value;
assert(H && toRemove);
value = hash((char *)toRemove, H->length);
removeElem_List(H->lists[value], toRemove);
}
void clear_Hash(Hash H){
unsigned int i;
assert(H);
for (i = 0; i < H->length; ++i)
clear_List(H->lists[i]);
}
void delete_Hash(Hash H){
unsigned int i;
assert(H);
for (i = 0; i < H->length; ++i)
delete_List(H->lists[i]);
free(H->lists);
free(H);
}
int find_Hash(Hash H, const void *toFind){
unsigned int value;
assert(H);
value = hash((char *)toFind, H->length);
if (find_List(H->lists[value], toFind))
return 1;
return 0;
}
void printBucket_Hash(Hash H, unsigned int index, FILE * stream){
assert(H && stream);
print_List(H->lists[index], stream);
}
void print_Hash(Hash H, FILE * stream){
unsigned int i;
for (i = 0; i < H->length; ++i)
if (begin_List(H->lists[i]))
printBucket_Hash(H, i, stream);
}
Hash resize_Hash(Hash H, unsigned int newLength){
List l;
List_Iter it;
unsigned int i;
Hash newHash;
assert(newLength);
newHash = new_Hash(newLength);
for (i = 0; i < H->length; ++i){
l = H->lists[i];
it = begin_List(l);
while (it != end_List(l)){
add_Hash(newHash, getElem_List(l, it));
it = next_List(l, it);
}
}
delete_Hash(H);
return newHash;
}
void resizeDouble_Hash(Hash *H){
assert(*H);
*H = resize_Hash(*H, (*H)->length * 2);
}
void resizeHalve_Hash(Hash *H){
assert(*H);
*H = resize_Hash(*H, (*H)->length / 2);
}
/**
* Functie de hash bazata pe djb2 a lui Dan Bernstein
* http://www.cse.yorku.ca/~oz/hash.html
* @return valoarea de dispersie (cheia)
*/
unsigned int hash(const char *str, unsigned int hash_length)
{
unsigned int hash = 5381;
int c;
while ( (c = *str++) != 0 )
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return (hash % hash_length);
}