hash function...

Started by
1 comment, last by Extrarius 18 years, 11 months ago
Hi, Usually, I use chars or strings as keys to a hash table... what if I want to use integers as keys? How should my hash function be like? A simple mod? Thanks
"Through me the road to the city of desolation,Through me the road to sorrows diuturnal,Through me the road among the lost creation."
Advertisement
edit - sorry, key not hash ;p

Hi.
For integers, you can just use
Hash = Key % TableSize
a more general solution can be to reinterpret whatever data you have as an array of characters, and them sum the ascii values. This is obviously going to be slower than a solution tailored to the data type, but it means you can do things like write a template to wrap a hash table up.
Heres a hashing function i just wrote, lifted from a c++ template
(T is the key type, U is the value type)

template <class T, class U>int HashTable<T,U>::Hash (T Element){	//Interpret element as an array of characters	int ElementSize = sizeof (T) ;	unsigned char * TheElement = reinterpret_cast <unsigned char *> (&Element) ;		//Summate the ascii values of each character	int iTotal = 0 ;	for (int i = 0 ; i < ElementSize ; i++)	{		iTotal += (int) TheElement  ;	} ;	//Convert to hash value	int Hash = (iTotal % TableSize) ;	return Hash ;} ;


[Edited by - fosh on May 23, 2005 8:53:13 AM]
I another similar thread, hplus0603 suggested the PhongHash algorithm:
unsigned int PhongHash( unsigned char const * data, size_t size ){   unsigned int hash = 0;   while( size-- > 0 ) {      hash = 0x63c63cd9*hash + *data + 0x9c39c33d;      ++data;   }   return hash;}


It will work for any kind of data by just using PhongHash((unsigned char *)&Object, sizeof(Object)) where object can be any variable. I can't say how well it would do though, as I haven't used it myself.
"Walk not the trodden path, for it has borne it's burden." -John, Flying Monk

This topic is closed to new replies.

Advertisement