gpt4 book ai didi

c++ - 我如何编写用于字符串的双哈希实现?

转载 作者:太空宇宙 更新时间:2023-11-04 11:57:05 27 4
gpt4 key购买 nike

大家好,第一次来这里,但我想首先问一下我对双重哈希的理解是否正确。

双重散列的工作原理是首先实现散列函数,然后检查该点是否已打开。如果当前点未打开,则使用第二个哈希函数确定另一个点,然后将其乘以当前尝试,然后将其添加到由第一个哈希算法确定的索引点。

我现在的代码是:

unsigned int findPos(hashedObj& x)
{
int offset = 1;
int iteration = 0;
unsigned int originalPos = myhash1( x );
unsigned int index = originalPos;
unsigned int secondPos = myhash2( x );
while( array[ index ].info != EMPTY && array[ index ].element != x )
{
iteration = offset++ * secondPos;
if ( ( originalPos + iteration ) > array.size( ) )
index = ( originalPos + iteration ) % array.size( );
else
index = originalPos + iteration;
}
return ( index );
}

unsigned int hash1( const string& key, const int Tsize )
{
//start the hashvalue at 0
unsigned int hashVal = 0;

//cout<<" the size of the table is: "<< Tsize <<endl;

//add the ascii value for every word to hashval, multiply by 37 each time
for ( int i = 0; i < key.length(); i++ )
hashVal = 37 * hashVal + key[ i ];
//mod hashval so it remains smaller than the table size
hashVal %= Tsize;

//return the itemes index value
return hashVal;
}

我刚刚意识到我没有包含我的第二个哈希函数

unsigned int hash2( const string& key, const int Tsize )
{
//store the sum of ascii numerical values
int hashVal = 0;

//add the values of all chars while multiplying each one with a prime number
for ( int i = 0; i < key.length(); i++ )
hashVal = 29 * hashVal + key[ i ];

//mod the hashed value with a prime smaller than the table size, subtract that number
//with the prime just used and return that value
unsigned int index = 44497 - ( hashVal % 44497 );

return index;
}

它可能看起来不像,但在实际交易中 tsize 被正确调用。

最佳答案

您的 if 语句不正确:

if ( ( originalPos + iteration ) > array.size( ) )
index = ( originalPos + iteration ) % array.size( );
else
index = originalPos + iteration;
}

应该是:

if ( ( originalPos + iteration ) >= array.size( ) )
index = ( originalPos + iteration ) % array.size( );
else
index = originalPos + iteration;
}

或者更好的是,因为你通过执行 if 而浪费的不仅仅是 % op,而且无论如何答案都是一样的,你可以完全摆脱 if:

index = ( originalPos + iteration ) % array.size( );

关于c++ - 我如何编写用于字符串的双哈希实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15771738/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com