-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashmap.c
100 lines (81 loc) · 2.29 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct KeyValuePair {
char* key;
char* value;
} KeyValuePair;
typedef struct HashMap {
int capacity;
KeyValuePair** pairs;
} HashMap;
// Hash function (simple string hashing based on character sum)
int hash_function(const char* key, int capacity) {
int hash = 0;
while (*key) {
hash += (int)*key;
key++;
}
return hash % capacity;
}
HashMap* create_hashmap(int capacity) {
HashMap* map = malloc(sizeof(HashMap));
map->capacity = capacity;
// Allocate memory for the array of pairs (pointers to linked lists)
map->pairs = malloc(sizeof(KeyValuePair*) * capacity);
for (int i = 0; i < capacity; i++) {
map->pairs[i] = NULL;
}
return map;
}
void trim_newline(char *str) {
char *pos = strchr(str, '\n');
if (pos != NULL) {
*pos = '\0';
}
}
void insert(HashMap* map, const char* key, char* value) {
int index = hash_function(key, map->capacity);
KeyValuePair* new_pair = malloc(sizeof(KeyValuePair));
new_pair->key = malloc(strlen(key) + 1); // Allocate memory for the key string
strcpy(new_pair->key, key);
trim_newline(value);
new_pair->value = value;
map->pairs[index] = new_pair;
}
char* get_value(HashMap* map, const char* key) {
int index = hash_function(key, map->capacity);
KeyValuePair* current = map->pairs[index];
if (current == NULL) {
return NULL;
}
return current->value;
}
void remove_pair(HashMap* map, const char* key) {
int index = hash_function(key, map->capacity);
KeyValuePair* current = map->pairs[index];
if (current != NULL) {
map->pairs[index] = NULL;
}
}
void remove_all_pairs(HashMap* map) {
for (int i = 0; i < map->capacity; i++) {
KeyValuePair *current = map->pairs[i];
if (current != NULL) {
map->pairs[i] = NULL;
}
}
}
void destroy_hashmap(HashMap* map) {
free(map);
}
// Print the contents of the hashmap (for debugging)
void print_hashmap(HashMap* map) {
for (int i = 1; i <= map->capacity; i++) {
KeyValuePair* current = map->pairs[i];
if (current != NULL) {
printf("Pair %2d: ", i);
printf("%s -> %s\n", current->key, current->value);
}
}
}