Hi, mates!
I'm trying to write a program to recognize a substring in a given string, using hashing. The common STL string methods doesnt work for me, because they are too slow.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
unsignedlong N = power(2,32)-1;
unsignedlong d = 107;
unsignedint HashFunction(char* key)
{
type result =0 ;
int i=0;
while(key[i])
{
result+= (power(d,i)*key[i++]) % N;
cout<<result<<endl;
}
return result;
}
}
I don't know if my hash function is well written, its my first try. Can anybody suggest me how to continue recognising a substring using that function ?
Thank you in advance!
PS: the function "power" is equivalent with pow, but works for int.
Yeah, I think the STL string methods are fast enough. It's your hash function that is terribly slow.
The first time through the loop you compute 107^0
The second time you compute 107^1
The third time you compute 107^2
etc.
Since your power function is probably just a loop, you have n^2 multiplies just in power() to hash a string of length n. You need to store an intermediate result so you don't have to compute it from scratch every time.
Yeah, i agree the power function is a stupid idea i gues...
I already tryed the STL string methods but i have a time limit for the task and they told me i have to use hashing to perform it faster. So hashing is really faster than string methods.
Determining the strength of hash functions is left to cryptologists. I'd recommend using one already out there such as SHA1, MD5, etc. (Be aware that both have been cracked though).