by bArray · 4y ago · 0 comments
First is a 'reasonable' hash function (although with a few more lines you can do better [1]):
unsigned int H(char* s){ int h; for(h = 0; *s; s++) h = ((h << 5) + h) + *s; return h; }
And then to build your hash table: int L = <table length>; // Large enough to reduce collisions
char** t = (char**)malloc(L * sizeof(char*));
memset(t, 0, L * sizeof(char*)); // Set it all to empty by default
Then to use it: /* Put example */
t[H("key string") % L] = "value string";
/* Get example */
char* v = t[H("some key") % L];
if(v) printf("value -> %s\n", v);
/* Remove example */
t[H("another key") % L] = NULL;
For them most part you can get pretty far with just this in C.[1] https://coffeespace.org.uk/projects/hash-functions-part-2.ht...
typedef struct{ char* k; char* v; } KV;
int L = <table length>; // Large enough to reduce collisions
KV* t = (KV*)malloc(L * sizeof(KV));
memset(t, 0, L * sizeof(KV)); // Set it all to empty by default
Then: /* Put example (detect collisions) */
char* k;
if(t[H(k) % L] == NULL || strcmp(t[H(k) % L].k, k) == 0)
t[H(k) % L] = "value string";
else
printf("Collision\n"); // Handle as you like
Of course this can get more and more advanced. The point wasn't to make a zero-collision table, it was just something that could be used quickly.