Skip to content

Commit 762fa26

Browse files
authored
Merge pull request vJechsmayr#117 from fahad-israr/master
Create RabinKarp.js
2 parents 4fd01a7 + 28435c2 commit 762fa26

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

‎Strings/RabinKarp.js‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import PolynomialHash from '../../cryptography/polynomial-hash/PolynomialHash';
2+
3+
/**
4+
* @param {string} text - Text that may contain the searchable word.
5+
* @param {string} word - Word that is being searched in text.
6+
* @return {number} - Position of the word in text.
7+
*/
8+
export default function rabinKarp(text, word) {
9+
const hasher = new PolynomialHash();
10+
11+
// Calculate word hash that we will use for comparison with other substring hashes.
12+
const wordHash = hasher.hash(word);
13+
14+
let prevFrame = null;
15+
let currentFrameHash = null;
16+
17+
// Go through all substring of the text that may match.
18+
for (let charIndex = 0; charIndex <= (text.length - word.length); charIndex += 1) {
19+
const currentFrame = text.substring(charIndex, charIndex + word.length);
20+
21+
// Calculate the hash of current substring.
22+
if (currentFrameHash === null) {
23+
currentFrameHash = hasher.hash(currentFrame);
24+
} else {
25+
currentFrameHash = hasher.roll(currentFrameHash, prevFrame, currentFrame);
26+
}
27+
28+
prevFrame = currentFrame;
29+
30+
// Compare the hash of current substring and seeking string.
31+
// In case if hashes match let's make sure that substrings are equal.
32+
// In case of hash collision the strings may not be equal.
33+
if (
34+
wordHash === currentFrameHash
35+
&& text.substr(charIndex, word.length) === word
36+
) {
37+
return charIndex;
38+
}
39+
}
40+
41+
return -1;
42+
}

0 commit comments

Comments
 (0)