forked from kaloi-noggins/trabson-eda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashmap.c
121 lines (98 loc) · 2.04 KB
/
hashmap.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
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "hashmap.h"
#include "avltree.h"
/**
* Função padronizada para calcular o hash de uma string.
*/
unsigned long elf_hash(const char *s)
{
unsigned long h = 0;
for (int i = 0; i < strlen(s); i++)
{
h = (h << 4) + s[i];
unsigned long x = h & 0xF0000000;
if (x != 0)
{
h ^= x >> 24;
h &= ~x;
}
}
return h;
}
struct bucket
{
avltree *hashtree;
};
struct hashmap
{
int capacity;
avltree **buckets;
};
hashmap *hashmap_create(int capacity)
{
if (capacity < 1) return NULL;
hashmap *map = malloc(sizeof(hashmap));
map->capacity = capacity;
map->buckets = malloc(sizeof(avltree*) * capacity);
return map;
}
void hashmap_set(hashmap *map, const char *key, int value)
{
int index = elf_hash(key) % map->capacity;
printf("index: %03d | key: %s | hash:%ld | value: %d\n", index, key, elf_hash(key), value);
if (map->buckets[index] == NULL)
{
map->buckets[index] = avltree_create();
}
avltree_insert(map->buckets[index], key, value);
printf("size: %d\n", avltree_size(map->buckets[index]));
}
int hashmap_get(hashmap *map, const char *key)
{
int index = elf_hash(key) % map->capacity;
if (map->buckets[index])
{
return avltree_lookup(map->buckets[index], key);
}
return 0;
}
bool hashmap_has(hashmap *map, const char *key)
{
int index = elf_hash(key) % map->capacity;
if (map->buckets[index])
{
return avltree_lookup(map->buckets[index], key)?true:false;
}
return false;
}
void hashmap_remove(hashmap *map, const char *key)
{
int index = elf_hash(key) % map->capacity;
if(map->buckets[index]) avltree_remove(map->buckets[index],key);
}
int hashmap_size(hashmap *map)
{
int count = 0;
for (int i = 0; i < map->capacity; i++)
{
if (map->buckets[i])
{
count += avltree_size(map->buckets[i]);
}
}
return count;
}
void hashmap_delete(hashmap *map)
{
for (int i = 0; i < map->capacity; i++)
{
if (map->buckets[i])
{
avltree_delete(map->buckets[i]);
}
}
free(map->buckets);
free(map);
}