Jump to content
  • Advertisement
Sign in to follow this  
FreJa

hash function...

This topic is 4748 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!