I made this function to teach myself about hash tables. Any ideas? I commented out free(addition)
because it was giving me a compiler error, but I need to figure out how to deallocate the memory.
#define hashSize 1000
typedef struct hashElem{
char* date;
char* holiday;
}hashElem;
typedef struct hash{
struct hashElem element;
struct hash* next;
}hash;
hash* hashTable[hashSize];
// Hash function
size_t murmurHash(const void *keyPtr, size_t keySize)
{
/* DESCRIPTION: Very fast string hashing algorithm with excelleng distribution and
* collision resistance. This source code has been released into the public
* domain.
*
* NOTES: http://murmurhash.googlepages.com
*
* RETURNS: Hashtable index for the key
*
*/
/* 'm' and 'r' are mixing constants generated offline. */
/* They're not really 'magic', they just happen to work well. */
const unsigned int m = 0x5bd1e995;
const int r = 24;
size_t hashValue = 0;
/* Mix 4 bytes at a time into the hash */
const unsigned char * data = (const unsigned char *)keyPtr;
while(keySize >= 4)
{
unsigned int k = *(unsigned int *) data;
k *= m;
k ^= k >> r;
k *= m;
hashValue *= m;
hashValue ^= k;
data += 4;
keySize -= 4;
}
/* Handle the last few bytes of the input array */
switch(keySize)
{
case 3: hashValue ^= data[2] << 16;
case 2: hashValue ^= data[1] << 8;
case 1: hashValue ^= data[0];
hashValue *= m;
};
/* Do a few final mixes of the hash to ensure the last few */
/* bytes are well-incorporated. */
hashValue ^= hashValue >> 13;
hashValue *= m;
hashValue ^= hashValue >> 15;
return (hashValue % hashSize);
}
// strlen: return length of string
int strlen(char *s)
{
char* p = s;
while (*p != '\0')
++p;
return p - s;
}
// Add Holiday into hash table
void addHoliday(char* date, char* holiday)
{
char* key;
int keyLen;
size_t keyHash;
hash* addition = malloc(sizeof(*addition));
key = date;
addition->element.date = key;
addition->element.holiday = holiday;
// Add holiday to Hash Table
if (hashTable[murmurHash(key, strlen(key))] == NULL)
{
addition->next = NULL;
hashTable[murmurHash(key, strlen(key))] = addition;
}
else //If there is already an element at the index, add current holiday to beginning of list
{
addition->next = hashTable[murmurHash(key, strlen(key))];
hashTable[murmurHash(key, strlen(key))] = addition;
}
//free(addition);
}
// If a date is entered, retrieve holiday from hash function index
char* getHoliday(char* date)
{
return(hashTable[murmurHash(date, strlen(date))]->element.holiday);
}
void main(void)
{
addHoliday("01/01/13", "New Years Day");
printf("%s\n", getHoliday("01/01/13"));
getchar();
}