Rabin-Karp 不适用于大素数给出错误的输出

问题描述

所以我正在解决 this 问题(rabin Karp 的算法)并编写了这个解决方案:

private static void searchPattern(String text,String pattern) {
    int txt_len = text.length(),pat_len = pattern.length();
    int hash_pat = 0,hash_txt = 0; // hash values for pattern and text's substrings
    final int mod = 100005;         // prime number to calculate modulo... larger modulo denominator reduces collisions in hash
    final int d = 256;              // to include all the ascii character codes
    int coeff = 1;                  // stores the multiplier (or coeffecient) for the first index of the sliding window

    /* 
     * HASHING PATTERN:
     * say text    = "abcd",then
     * hashed text = 256^3 *'a' + 256^2 *'b' + 256^1 *'c' + 256^0 *'d'
     */

    // The value of coeff would be "(d^(pat_len - 1)) % mod"
    for (int i = 0; i < pat_len - 1; i++)
        coeff = (coeff * d) % mod;

    // calculate hash of the first window and the pattern itself
    for (int i = 0; i < pat_len; i++) {
        hash_pat = (d * hash_pat + pattern.charat(i)) % mod;
        hash_txt = (d * hash_txt + text.charat(i)) % mod;
    }

    for (int i = 0; i < txt_len - pat_len; i++) {
        if (hash_txt == hash_pat) {
            // our chances of collisions are quite less (1/mod) so we dont need to recheck the substring
            System.out.println("Pattern found at index " + i);
        }
        hash_txt = (d * (hash_txt - text.charat(i) * coeff) + text.charat(i + pat_len)) % mod; // calculating next window (i+1 th index)

        // We might get negative value of t,converting it to positive
        if (hash_txt < 0)
            hash_txt = hash_txt + mod;
    }
    if (hash_txt == hash_pat) // checking for the last window
        System.out.println("Pattern found at index " + (txt_len - pat_len));
}

现在,如果 mod = 1000000007,此代码根本无法工作,而一旦我们采用其他素数(足够大,如 1e5+7),代码就会神奇地开始工作!

代码逻辑失败的那一行是:

hash_txt = (d * (hash_txt - text.charat(i) * coeff) + text.charat(i + pat_len)) % mod;

谁能告诉我为什么会这样???也许这是一个愚蠢的疑问,但我就是不明白。

解决方法

在 Java 中,int 是一个 32 位整数。如果使用此类数字的计算在数学上产生需要更多二进制数字的结果,则额外的数字将被默默丢弃。这称为溢出。

为了避免这种情况,Rabin-Karp 算法在每个步骤中以某个素数为模减少结果,从而使数字保持足够小,以便下一步不会溢出。为此,所选择的素数必须适当地小

d * (hash + max(char) * coeff) + max(char)) < max(int)

自从

0 ≤ hash 1 ≤ 系数 max(char) = 216
max(int) = 231

任何小于 27=128 的质数都可以。对于较大的质数,这取决于它们的系数最终是多少,但即使我们选择一个具有最小可能的 coeff = 1 的质数,该质数也不能超过 223,这远小于质数你用过。

因此,在实践中,人们使用 Rabin-Karp 的整数数据类型比字符类型大得多,例如 long(64 位)。然后,任何质数 39 都可以。

即便如此,如果值得注意的是你的推理

我们发生冲突的机会相当少(1/mod),所以我们不需要重新检查子字符串

是有缺陷的,因为概率不是由偶然决定的,而是由被检查的字符串决定的。除非您知道输入的概率分布,否则您无法知道失败的概率是多少。这就是 Rabin-Karp 重新检查字符串以确保的原因。