forked from victorgorgonho/SpellCheckerInC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hashTable_sll.c
125 lines (101 loc) · 2.98 KB
/
hashTable_sll.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
#include "hashTable_sll.h"
unsigned Hash(char *key) { //String hashing from K&R's "The C Programming Language"
unsigned hash;
for (hash = 0; *key != '\0'; key++)
hash = *key + 31 * hash;
return hash % MAX_BUCKETS;
}
HashTable* CreateHashTable() {
HashTable *h = (HashTable*) malloc (sizeof(HashTable));
for(int i = 0; i < MAX_BUCKETS; i++) {
h->buckets[i] = NULL;
h->numElements[i] = 0;
}
return h;
}
void Insert(HashTable *hashTable, char *key) { //Using chaining probing to handle collisions.
if (!hashTable)
hashTable = CreateHashTable();
unsigned hashValue = Hash(key);
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->key = (char*) malloc(MAX_STRING * sizeof(char));
strcpy(newNode->key, key);
newNode->next = NULL;
if(!hashTable->buckets[hashValue]){
hashTable->buckets[hashValue] = newNode;
hashTable->numElements[hashValue]++;
}else{
struct Node* aux = hashTable->buckets[hashValue];
while(aux->next){
aux = aux->next;
//printf("%s [%d]\n", aux->key, hashValue); //Uncomment if you want to print collisions.
}
aux->next = newNode;
hashTable->numElements[hashValue]++;
}
}
bool Search(HashTable *hashTable, char *key) {
struct Node *aux;
unsigned hashValue = Hash(key);
if (!hashTable) {
printf("Hash Table is empty.\n");
return false;
}
aux = hashTable->buckets[hashValue];
while(aux){
if (strcmp(aux->key, key) == 0)
return true;
aux = aux->next;
}
//printf("%s [%d]\n", key, hashValue = Hash(key)); //Uncomment if you want to print not found words.
return false;
}
void RemovePunctAndMakeLowerCase(char *key) {
char *src = key, *dst = key;
while (*src) {
if (ispunct((unsigned char)*src)) {
/* Skip this character */
src++;
}
else if (isupper((unsigned char)*src)) {
/* Make it lowercase */
*dst++ = tolower((unsigned char)*src);
src++;
}
else if (src == dst) {
/* Increment both pointers without copying */
src++;
dst++;
}
else {
/* Copy character */
*dst++ = *src++;
}
}
*dst = 0;
}
/*
unsigned Hash(char *key) { //Djb2 hashing
unsigned long hash = 5381;
int c;
while (c = *key++)
hash = ((hash << 5) + hash) + c;
return hash % MAX_BUCKETS;
}
*/
/*
unsigned Hash(char *key) { //Jenkins Hashing
size_t i = 0;
unsigned long hash = 0;
size_t length = strlen(key);
while (i != length) {
hash += key[i++];
hash += hash << 10;
hash ^= hash >> 6;
}
hash += hash << 3;
hash ^= hash >> 11;
hash += hash << 15;
return hash % MAX_BUCKETS;
}
*/