Click to See Complete Forum and Search --> : Implementing Hash Function without MOD?


Shanin
October 14th, 2004, 01:41 AM
Is there a way to implement Hash Function without MOD function?
I cannot guess that there is another way.

j0nas
October 14th, 2004, 03:26 AM
Of course there is... A hash function is just a way to generate a value (does not even have to be unique) out of some data. If the data is a string for instance, a very simple string hash function could be:

int hashstring(const char *str)
{
int hash;
for (hash = 0; *str; str++)
hash += *str;
return hash;
}

(The above code may not be the best string hash function, it is just an example.)

DeepButi
October 14th, 2004, 04:57 AM
j0nas,
correct answer ... but useless ;) as a hash value is usually used to access a table with a not infinite length, so it must be converted to a value in the range 0,table_size-1 and here MOD comes as the best(?) method.

(Useless message also :eek: )

j0nas
October 14th, 2004, 05:09 AM
j0nas,
correct answer ... but useless ;) as a hash value is usually used to access a table with a not infinite length, so it must be converted to a value in the range 0,table_size-1 and here MOD comes as the best(?) method.

(Useless message also :eek: )

True but not... My hash string example could be used as a key: instead of storing variable-sized strings, we store INTs. This has nothing to do with the actual hash table.

But sure, normally you do MOD because you want an array index.

yuwaraj
October 21st, 2004, 03:52 AM
Hi,
let me clear first u wanted
location=( hash_value % 10) , hash_value is returned by any hash_function and 10 is ur max limit
is that right ?
Then u r just need to know the range of ur (array say) i.e Index in that array should not
cross array length so u can write ur won function to calculate it using other operators.

Yves M
October 23rd, 2004, 09:37 AM
You could eliminate the MOD by making the hash table size a power of 2 and then use bitwise and to get the index. As in:

index = hash_value & 0xFF // for 256 slots

BUT, this is not a good idea, since in general, you will get many more collisions than if the size of your hash table is a prime number. So the performance will degenerate pretty badly.