tags:

views:

103

answers:

3

I've tried everything. Even java's forumla:

java.lang.String.hashCode():

s[0]*(31^(n-1)) + s[1]*(31^(n-2)) + ... + s[n-1]

I've interpretted this as a sum: Although I am not quite sure what to do with the s[n-1];

int hashmap::hashstr( const char*const str )
{
    int result = 0;
    int i = 0;
    int j = 0;
    int k = 0;
    unsigned n = 0;
    for ( ; str[n] != NULL; ++n ); // how many characters?

    while ( j != n ) // no more characters
    {
        result += str[i] * ( 31 ^ ( n - k ) );
        j++;
        i++;
        k++;
    }
    return result % maxSize;
}

where maxSize is the 10th element in my fixed array size of 11.

What am i doing wrong? SOME of my hash indicies are coming out wrong. Others, correctly. Why is this? So far everyones been like, "Who cares how it works!! Use a template!" Well, I want to understand this..

+3  A: 
unsigned n = 0;
for ( ; str[n] != NULL; ++n ); // how many characters?

You know you could just use strlen(str), right?

And the line:

return result % maxSize;

Where's this result from? I don't see any result variable.

Nick Bedford
I was told that using strlen(str) in a loop is bad programming practi b/c of enumerants..
@lampshade, What are you talking about? You don't put strlen() in a loop. You find the size of the string intially, it has nothing to do with your loop.
Simucal
It is a bad practice using strlen() where you actually walk through the string anyway, because the strlen() function itself walks through the string once in the first place. Maybe it's not that significant in this case, but in any code where you actually go through the string anyway, generally better practice just to test the current character with '\0' to find out are you at the end. This is kinda a thumb-rule of string processing with ASCIIZ.
progician
@progician Yeah I was merely addressing the manual length calculation. I've suggested what you stated above in another answer anyway.
Nick Bedford
+7  A: 
s[0](31^(n-1)) + s[1](31^(n-2)) + ... + s[n-1]

In the formula ^ indicates exponentiation, not the bitwise xor operation.
Check out this SO question.

Nick D
A: 

Just going from this code, you could do the following:

void function (const char *str)
{
    while (*str)
    {
        /* process whatever with *str which is the same as str[i] in a for loop */
        str++;
    }
}

Also, you don't need the second const on those const char *const parameters. const char * is fine.

Nick Bedford