暴雪的hash算法

来源:互联网 发布:上海python培训班 编辑:程序博客网 时间:2024/04/29 18:09

值得一提的是,在解决Hash冲突的时候,搞的焦头烂额,结果今天上午在自己的博客内的一篇文章(十一、从头到尾彻底解析Hash表算法)内找到了解决办法:网上流传甚广的暴雪的Hash算法。 OK,接下来,咱们回顾下暴雪的hash表算法:

接下来,咱们来具体分析一下一个最快的Hash表算法。
我们由一个简单的问题逐步入手:有一个庞大的字符串数组,然后给你一个单独的字符串,让你从这个数组中查找是否有这个字符串并找到它,你会怎么做?
有一个方法最简单,老老实实从头查到尾,一个一个比较,直到找到为止,我想只要学过程序设计的人都能把这样一个程序作出来,但要是有程序员把这样的程序交给用户,我只能用无语来评价,或许它真的能工作,但...也只能如此了。
最合适的算法自然是使用HashTable(哈希表),先介绍介绍其中的基本知识,所谓Hash,一般是一个整数,通过某种算法,可以把一个字符串"压缩" 成一个整数。当然,无论如何,一个32位整数是无法对应回一个字符串的,但在程序中,两个字符串计算出的Hash值相等的可能非常小,下面看看在MPQ中的Hash算法:
    函数prepareCryptTable以下的函数生成一个长度为0x500(合10进制数:1280)的cryptTable[0x500]

  1. //函数prepareCryptTable以下的函数生成一个长度为0x500(合10进制数:1280)的cryptTable[0x500]  
  2. void prepareCryptTable()  
  3. {   
  4.     unsigned long seed = 0x00100001, index1 = 0, index2 = 0, i;  
  5.   
  6.     for( index1 = 0; index1 < 0x100; index1++ )  
  7.     {   
  8.         for( index2 = index1, i = 0; i < 5; i++, index2 += 0x100 )  
  9.         {   
  10.             unsigned long temp1, temp2;  
  11.   
  12.             seed = (seed * 125 + 3) % 0x2AAAAB;  
  13.             temp1 = (seed & 0xFFFF) << 0x10;  
  14.   
  15.             seed = (seed * 125 + 3) % 0x2AAAAB;  
  16.             temp2 = (seed & 0xFFFF);  
  17.   
  18.             cryptTable[index2] = ( temp1 | temp2 );   
  19.         }   
  20.     }   
  21. }   

    函数HashString以下函数计算lpszFileName 字符串的hash值,其中dwHashType 为hash的类型,

  1. //函数HashString以下函数计算lpszFileName 字符串的hash值,其中dwHashType 为hash的类型,  
  2. unsigned long HashString(const char *lpszkeyName, unsigned long dwHashType )  
  3. {  
  4.     unsigned char *key  = (unsigned char *)lpszkeyName;  
  5.     unsigned long seed1 = 0x7FED7FED;  
  6.     unsigned long seed2 = 0xEEEEEEEE;  
  7.     int ch;  
  8.   
  9.     while( *key != 0 )  
  10.     {  
  11.         ch = *key++;  
  12.         seed1 = cryptTable[(dwHashType<<8) + ch] ^ (seed1 + seed2);  
  13.         seed2 = ch + seed1 + seed2 + (seed2<<5) + 3;  
  14.     }  
  15.     return seed1;  
  16. }  

    Blizzard的这个算法是非常高效的,被称为"One-Way Hash"( A one-way hash is a an algorithm that is constructed in such a way that deriving the original string (set of strings, actually) is virtually impossible)。举个例子,字符串"unitneutralacritter.grp"通过这个算法得到的结果是0xA26067F3。
 是不是把第一个算法改进一下,改成逐个比较字符串的Hash值就可以了呢,答案是,远远不够,要想得到最快的算法,就不能进行逐个的比较,通常是构造一个哈希表(Hash Table)来解决问题,哈希表是一个大数组,这个数组的容量根据程序的要求来定义,
     例如1024,每一个Hash值通过取模运算 (mod) 对应到数组中的一个位置,这样,只要比较这个字符串的哈希值对应的位置有没有被占用,就可以得到最后的结果了,想想这是什么速度?是的,是最快的O(1),现在仔细看看这个算法吧:
  1. typedef struct  
  2. {  
  3.     int nHashA;  
  4.     int nHashB;  
  5.     char bExists;  
  6.    ......  
  7. } SOMESTRUCTRUE;  
  8. //一种可能的结构体定义?  
    函数GetHashTablePos下述函数为在Hash表中查找是否存在目标字符串,有则返回要查找字符串的Hash值,无则,return -1.
  1. //函数GetHashTablePos下述函数为在Hash表中查找是否存在目标字符串,有则返回要查找字符串的Hash值,无则,return -1.  
  2. int GetHashTablePos( har *lpszString, SOMESTRUCTURE *lpTable )   
  3. //lpszString要在Hash表中查找的字符串,lpTable为存储字符串Hash值的Hash表。  
  4. {   
  5.     int nHash = HashString(lpszString);  //调用上述函数HashString,返回要查找字符串lpszString的Hash值。  
  6.     int nHashPos = nHash % nTableSize;  
  7.    
  8.     if ( lpTable[nHashPos].bExists  &&  !strcmp( lpTable[nHashPos].pString, lpszString ) )   
  9.     {  //如果找到的Hash值在表中存在,且要查找的字符串与表中对应位置的字符串相同,  
  10.         return nHashPos;    //返回找到的Hash值  
  11.     }   
  12.     else  
  13.     {  
  14.         return -1;    
  15.     }   
  16. }  
    看到此,我想大家都在想一个很严重的问题:“如果两个字符串在哈希表中对应的位置相同怎么办?”,毕竟一个数组容量是有限的,这种可能性很大。解决该问题的方法很多,我首先想到的就是用“链表”,感谢大学里学的数据结构教会了这个百试百灵的法宝,我遇到的很多算法都可以转化成链表来解决,只要在哈希表的每个入口挂一个链表,保存所有对应的字符串就OK了。事情到此似乎有了完美的结局,如果是把问题独自交给我解决,此时我可能就要开始定义数据结构然后写代码了。
    然而Blizzard的程序员使用的方法则是更精妙的方法。基本原理就是:他们在哈希表中不是用一个哈希值而是用三个哈希值来校验字符串。

    MPQ使用文件名哈希表来跟踪内部的所有文件。但是这个表的格式与正常的哈希表有一些不同。首先,它没有使用哈希作为下标,把实际的文件名存储在表中用于验证,实际上它根本就没有存储文件名。而是使用了3种不同的哈希:一个用于哈希表的下标,两个用于验证。这两个验证哈希替代了实际文件名。
    当然了,这样仍然会出现2个不同的文件名哈希到3个同样的哈希。但是这种情况发生的概率平均是:1:18889465931478580854784,这个概率对于任何人来说应该都是足够小的。现在再回到数据结构上,Blizzard使用的哈希表没有使用链表,而采用"顺延"的方式来解决问题。下面,咱们来看看这个网上流传甚广的暴雪hash算法:
    函数GetHashTablePos中,lpszString 为要在hash表中查找的字符串;lpTable 为存储字符串hash值的hash表;nTableSize 为hash表的长度: 
  1. //函数GetHashTablePos中,lpszString 为要在hash表中查找的字符串;lpTable 为存储字符串hash值的hash表;nTableSize 为hash表的长度:   
  2. int GetHashTablePos( char *lpszString, MPQHASHTABLE *lpTable, int nTableSize )  
  3. {  
  4.     const int  HASH_OFFSET = 0, HASH_A = 1, HASH_B = 2;  
  5.    
  6.     int  nHash = HashString( lpszString, HASH_OFFSET );  
  7.     int  nHashA = HashString( lpszString, HASH_A );  
  8.     int  nHashB = HashString( lpszString, HASH_B );  
  9.     int  nHashStart = nHash % nTableSize;  
  10.     int  nHashPos = nHashStart;  
  11.    
  12.     while ( lpTable[nHashPos].bExists )  
  13.    {  
  14. //     如果仅仅是判断在该表中时候存在这个字符串,就比较这两个hash值就可以了,不用对结构体中的字符串进行比较。  
  15. //         这样会加快运行的速度?减少hash表占用的空间?这种方法一般应用在什么场合?  
  16.         if (   lpTable[nHashPos].nHashA == nHashA  
  17.         &&  lpTable[nHashPos].nHashB == nHashB )  
  18.        {  
  19.             return nHashPos;  
  20.        }  
  21.        else  
  22.        {  
  23.             nHashPos = (nHashPos + 1) % nTableSize;  
  24.        }  
  25.    
  26.         if (nHashPos == nHashStart)  
  27.               break;  
  28.     }  
  29.      return -1;  
  30. }  

    上述程序解释:

  1. 计算出字符串的三个哈希值(一个用来确定位置,另外两个用来校验)
  2. 察看哈希表中的这个位置
  3. 哈希表中这个位置为空吗?如果为空,则肯定该字符串不存在,返回-1。
  4. 如果存在,则检查其他两个哈希值是否也匹配,如果匹配,则表示找到了该字符串,返回其Hash值。
  5. 移到下一个位置,如果已经移到了表的末尾,则反绕到表的开始位置起继续查询 
  6. 看看是不是又回到了原来的位置,如果是,则返回没找到
  7. 回到3。

24.4、不重复Hash编码

    有了上面的暴雪Hash算法。咱们的问题便可解决了。不过,有两点必须先提醒读者:1、Hash表起初要初始化;2、暴雪的Hash算法对于查询那样处理可以,但对插入就不能那么解决。

    关键主体代码如下:

  1. //函数prepareCryptTable以下的函数生成一个长度为0x500(合10进制数:1280)的cryptTable[0x500]  
  2. void prepareCryptTable()  
  3. {  
  4.     unsigned long seed = 0x00100001, index1 = 0, index2 = 0, i;  
  5.   
  6.     for( index1 = 0; index1 <0x100; index1++ )  
  7.     {  
  8.         for( index2 = index1, i = 0; i < 5; i++, index2 += 0x100)  
  9.         {  
  10.             unsigned long temp1, temp2;  
  11.             seed = (seed * 125 + 3) % 0x2AAAAB;  
  12.             temp1 = (seed & 0xFFFF)<<0x10;  
  13.             seed = (seed * 125 + 3) % 0x2AAAAB;  
  14.             temp2 = (seed & 0xFFFF);  
  15.             cryptTable[index2] = ( temp1 | temp2 );  
  16.         }  
  17.     }  
  18. }  
  19.   
  20. //函数HashString以下函数计算lpszFileName 字符串的hash值,其中dwHashType 为hash的类型,  
  21. unsigned long HashString(const char *lpszkeyName, unsigned long dwHashType )  
  22. {  
  23.     unsigned char *key  = (unsigned char *)lpszkeyName;  
  24.     unsigned long seed1 = 0x7FED7FED;  
  25.     unsigned long seed2 = 0xEEEEEEEE;  
  26.     int ch;  
  27.   
  28.     while( *key != 0 )  
  29.     {  
  30.         ch = *key++;  
  31.         seed1 = cryptTable[(dwHashType<<8) + ch] ^ (seed1 + seed2);  
  32.         seed2 = ch + seed1 + seed2 + (seed2<<5) + 3;  
  33.     }  
  34.     return seed1;  
  35. }  
  36.   
  37. /////////////////////////////////////////////////////////////////////  
  38. //function: 哈希词典 编码  
  39. //parameter:  
  40. //author: lei.zhou  
  41. //time: 2011-12-14  
  42. /////////////////////////////////////////////////////////////////////  
  43. MPQHASHTABLE TestHashTable[nTableSize];  
  44. int TestHashCTable[nTableSize];  
  45. int TestHashDTable[nTableSize];  
  46. key_list test_data[nTableSize];  
  47.   
  48. //直接调用上面的hashstring,nHashPos就是对应的HASH值。  
  49. int insert_string(const char *string_in)  
  50. {  
  51.     const int HASH_OFFSET = 0, HASH_C = 1, HASH_D = 2;  
  52.     unsigned int nHash = HashString(string_in, HASH_OFFSET);  
  53.     unsigned int nHashC = HashString(string_in, HASH_C);  
  54.     unsigned int nHashD = HashString(string_in, HASH_D);  
  55.     unsigned int nHashStart = nHash % nTableSize;  
  56.     unsigned int nHashPos = nHashStart;  
  57.     int ln, ires = 0;  
  58.   
  59.     while (TestHashTable[nHashPos].bExists)  
  60.     {  
  61. //      if (TestHashCTable[nHashPos]  == (int) nHashC && TestHashDTable[nHashPos] == (int) nHashD)  
  62. //          break;  
  63. //      //...  
  64. //      else  
  65.         //如之前所提示读者的那般,暴雪的Hash算法对于查询那样处理可以,但对插入就不能那么解决  
  66.             nHashPos = (nHashPos + 1) % nTableSize;  
  67.   
  68.         if (nHashPos == nHashStart)  
  69.             break;  
  70.     }  
  71.   
  72.     ln = strlen(string_in);  
  73.     if (!TestHashTable[nHashPos].bExists && (ln < nMaxStrLen))  
  74.     {   
  75.         TestHashCTable[nHashPos] = nHashC;  
  76.         TestHashDTable[nHashPos] = nHashD;  
  77.   
  78.         test_data[nHashPos] = (KEYNODE *) malloc (sizeof(KEYNODE) * 1);  
  79.         if(test_data[nHashPos] == NULL)  
  80.         {  
  81.             printf("10000 EMS ERROR !!!!\n");  
  82.             return 0;  
  83.         }  
  84.   
  85.         test_data[nHashPos]->pkey = (char *)malloc(ln+1);  
  86.         if(test_data[nHashPos]->pkey == NULL)  
  87.         {  
  88.             printf("10000 EMS ERROR !!!!\n");  
  89.             return 0;  
  90.         }  
  91.   
  92.         memset(test_data[nHashPos]->pkey, 0, ln+1);  
  93.         strncpy(test_data[nHashPos]->pkey, string_in, ln);  
  94.         *((test_data[nHashPos]->pkey)+ln) = 0;  
  95.         test_data[nHashPos]->weight = nHashPos;  
  96.   
  97.         TestHashTable[nHashPos].bExists = 1;  
  98.     }  
  99.     else  
  100.     {  
  101.         if(TestHashTable[nHashPos].bExists)  
  102.             printf("30000 in the hash table %s !!!\n", string_in);  
  103.         else  
  104.             printf("90000 strkey error !!!\n");  
  105.     }  
  106.     return nHashPos;  
  107. }  

    接下来要读取索引文件big_index对其中的关键词进行编码(为了简单起见,直接一行一行扫描读写,没有跳过行数了):

  1. void bigIndex_hash(const char *docpath, const char *hashpath)  
  2. {  
  3.     FILE *fr, *fw;  
  4.     int len;  
  5.     char *pbuf, *p;  
  6.     char dockey[TERM_MAX_LENG];  
  7.   
  8.     if(docpath == NULL || *docpath == '\0')  
  9.         return;  
  10.   
  11.     if(hashpath == NULL || *hashpath == '\0')  
  12.         return;  
  13.   
  14.     fr = fopen(docpath, "rb");  //读取文件docpath  
  15.     fw = fopen(hashpath, "wb");  
  16.     if(fr == NULL || fw == NULL)  
  17.     {  
  18.         printf("open read or write file error!\n");  
  19.         return;  
  20.     }  
  21.   
  22.     pbuf = (char*)malloc(BUFF_MAX_LENG);  
  23.     if(pbuf == NULL)  
  24.     {  
  25.         fclose(fr);  
  26.         return ;  
  27.     }  
  28.   
  29.     memset(pbuf, 0, BUFF_MAX_LENG);  
  30.   
  31.     while(fgets(pbuf, BUFF_MAX_LENG, fr))  
  32.     {  
  33.         len = GetRealString(pbuf);  
  34.         if(len <= 1)  
  35.             continue;  
  36.         p = strstr(pbuf, "#####");    
  37.         if(p != NULL)  
  38.             continue;  
  39.   
  40.         p = strstr(pbuf, "  ");  
  41.         if (p == NULL)  
  42.         {  
  43.             printf("file contents error!");  
  44.         }  
  45.   
  46.         len = p - pbuf;  
  47.         dockey[0] = 0;  
  48.         strncpy(dockey, pbuf, len);  
  49.   
  50.         dockey[len] = 0;        
  51.   
  52.         int num = insert_string(dockey);   
  53.   
  54.         dockey[len] = ' ';  
  55.         dockey[len+1] = '\0';  
  56.         char str[20];  
  57.         itoa(num, str, 10);  
  58.   
  59.         strcat(dockey, str);  
  60.         dockey[len+strlen(str)+1] = '\0';  
  61.         fprintf (fw, "%s\n", dockey);  
  62.   
  63.     }  
  64.     free(pbuf);  
  65.     fclose(fr);  
  66.     fclose(fw);  
  67. }  

    主函数已经很简单了,如下:

  1. int main()  
  2. {  
  3.     prepareCryptTable();  //Hash表起初要初始化  
  4.   
  5.     //现在要把整个big_index文件插入hash表,以取得编码结果  
  6.     bigIndex_hash("big_index.txt""hashpath.txt");  
  7.     system("pause");  
  8.   
  9.     return 0;  
  10. }  
原创粉丝点击