我发现了一个来自that网站的rabin karp代码,并更改为尝试。更改的代码如下。你可以在hashtable.txt中看到单词和它们的散列值。下面的例子hashtable.txt似乎是正确的。Karp Rabin的素数和块长度
但是,当我将M(块长度)更改为150时,我得到错误的结果。例如在hashtable.txt中,第一行和第六行必须相同,但它们的散列值是不同的。
或者当我将q(素数)更改为683303时,它也会得到错误的结果。
rabin karp算法中素数与块长度之间的关系是什么?错误结果的原因是什么?
#include<stdio.h>
#include<string.h>
#include <fstream>
#include <iostream>
// d is the number of characters in input alphabet
#define d 256
int M = 80;
/*
txt -> text
q -> A prime number
*/
using namespace std;
void writeTable(char *txt, int q)
{
ofstream myfile;
myfile.open ("hashtable.txt");
int N = strlen(txt);
int i, j;
int t = 0; // hash value for txt
int h = 1;
// The value of h would be "pow(d, M-1)%q"
for (i = 0; i < M-1; i++)
h = (h*d)%q;
// Calculate the hash value of pattern and first window of text
for (i = 0; i < M; i++)
{
t = (d*t + txt[i])%q;
}
// Slide the pattern over text one by one
for (i = 0; i <= N - M; i++)
{
myfile << t <<" ";
for (long z = i; z < M+i; z++){myfile<<txt[z];}myfile<<"\n";
// Calulate hash value for next window of text: Remove leading digit,
// add trailing digit
if (i < N-M)
{
t = (d*(t - txt[i]*h) + txt[i+M])%q;
// We might get negative value of t, converting it to positive
if(t < 0)
t = (t + q);
}
}
myfile.close();
}
/* Driver program to test above function */
int main()
{
char *txt ="abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde";
int q = 683303; // A prime number
writeTable(txt, q);
printf("finish");
getchar();
return 0;
}
我试过d = 256 M = 40 q = 139907 so h = 53941.但INT_MAX /(d *(d-1))= 32896。毕竟它的工作是正确的。这个例子中h不小于32896,它应该给我错误的结果。那有什么问题? – Yavuz 2013-04-11 11:49:09
除了这个事实,即使在溢出后,你也可以通过纯粹的机会得到正确的结果(尽管如此,不要期望活着),在我的示例文本中,如果我没有忽略一个字符,并假定ASCII兼容编码(不知道EBCDIC的代码数字),最大的出现值是101 - 对于'e' - 因此,实际得到的最大产品是'53941 * 256 * 101 = 1394698496',它小于'2^31-1'。有了这些'q'和'M'值(因此'h'),如果整个输入是ASCII(即'<128'),就不会溢出。 – 2013-04-11 12:00:03