can-mohan 0 Junior Poster

Hi All,
I am writing hash function (similar to multimap concept of c++ : duplicate keys are allowed) in order to check the anagrams.
but i am not getting desired result . Could you suggest efficient solution for the same.

output:

key[148]:val[joy]
key[174]:val[jam]
key[294]:val[paula]
key[13]:val[ulrich]
key[174]:val[cat]
key[174]:val[act]
key[148]:val[yoj]
key[265]:val[vij]
key[265]:val[jiv]

here key value 174 is fine for strings act and cat (anagrams) but same can't be expected with jam.

below is the code snippet.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>


unsigned long hash(char *str, size_t size)
    {
        unsigned long hash_val = 5381;
        unsigned long  sum=0;
        char* val ;
        int i,j;


        for ( j=0;j<9;j++)
        {  val=malloc(strlen(str)+1);
           memset(val,'\0',strlen(str)+1);
           strcpy(val,str);
        for (i=0;val[i]!='\0';i++ )
           {

        sum=sum+val[i];


         }


        return size%sum;

    }

}


int main()
{

int i;
 char *str[9]={"joy","jam","paula","ulrich","cat","act","yoj","vij","jiv"};

unsigned long key;
size_t size=4542;// it may be anything just for test it is being used
for(i=0;i<9;i++)
{
key= hash(str[i],size);
printf("\nkey[%ld]:val[%s]",key,str[i]);
}
return 1;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.