-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperfecthashing.c
More file actions
117 lines (89 loc) · 2.74 KB
/
perfecthashing.c
File metadata and controls
117 lines (89 loc) · 2.74 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAXN 100
struct Node {
int key;
struct Node* next;
};
struct Bucket {
struct Node* chain;
};
struct PerfectHashTable {
int size;
struct Bucket* table;
};
struct HashFunction {
int a;
int b;
};
int hash(struct HashFunction hf, int key, int size) {
return ((hf.a * key + hf.b) % INT_MAX) % size;
}
struct PerfectHashTable* createPerfectHashTable(int* keys, int n) {
struct PerfectHashTable* pht = (struct PerfectHashTable*)malloc(sizeof(struct PerfectHashTable));
pht->size = n * n; // Size of the hash table is the square of the number of keys
// Allocate memory for the hash table
pht->table = (struct Bucket*)malloc(pht->size * sizeof(struct Bucket));
// Initialize buckets
for (int i = 0; i < pht->size; i++) {
pht->table[i].chain = NULL;
}
// Generate hash functions for each bucket
struct HashFunction* hashFunctions = (struct HashFunction*)malloc(pht->size * sizeof(struct HashFunction));
for (int i = 0; i < pht->size; i++) {
hashFunctions[i].a = rand() % (pht->size - 1) + 1; // a should be non-zero and less than the size
hashFunctions[i].b = rand() % pht->size;
}
// Insert keys into the perfect hash table
for (int i = 0; i < n; i++) {
int h1 = hash(hashFunctions[i], keys[i], pht->size);
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->key = keys[i];
newNode->next = pht->table[h1].chain;
pht->table[h1].chain = newNode;
}
free(hashFunctions);
return pht;
}
void printPerfectHashTable(struct PerfectHashTable* pht) {
printf("Perfect Hash Table:\n");
for (int i = 0; i < pht->size; i++) {
printf("%d: ", i);
struct Node* current = pht->table[i].chain;
while (current != NULL) {
printf("%d -> ", current->key);
current = current->next;
}
printf("NULL\n");
}
}
int main() {
int n;
printf("Enter the number of keys: ");
scanf("%d", &n);
if (n <= 0 || n > MAXN) {
printf("Invalid number of keys. Exiting.\n");
return 1;
}
int* keys = (int*)malloc(n * sizeof(int));
printf("Enter the keys:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &keys[i]);
}
struct PerfectHashTable* pht = createPerfectHashTable(keys, n);
printPerfectHashTable(pht);
// Free memory
for (int i = 0; i < pht->size; i++) {
struct Node* current = pht->table[i].chain;
while (current != NULL) {
struct Node* temp = current;
current = current->next;
free(temp);
}
}
free(pht->table);
free(pht);
free(keys);
return 0;
}