Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions Search/RabinKarp.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,23 @@ function rabinKarpSearch(text, pattern) {
// Calculate the hash of the first substring in the text
hashText[0] = hash(text, patternLength)

// Precompute BASE^(patternLength-1) % MOD
const basePow = Math.pow(BASE, patternLength - 1) % MOD
// Precompute BASE^(patternLength-1) % MOD step by step, so that it stays exact
// (Math.pow loses precision once BASE^(patternLength-1) exceeds 2^53)
let basePow = 1
for (let i = 1; i < patternLength; i++) {
basePow = (basePow * BASE) % MOD
}

// The first window (index 0) has to be checked as well
if (
textLength >= patternLength &&
hashText[0] === hashPattern &&
text.substring(0, patternLength) === pattern
) {
indices.push(0)
}

for (let i = 1; i <= textLength - patternLength + 1; i++) {
for (let i = 1; i <= textLength - patternLength; i++) {
// Update the rolling hash by removing the first character
// and adding the next character in the text
hashText[i] =
Expand Down
19 changes: 18 additions & 1 deletion Search/test/RabinKarp.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ describe('Rabin-Karp Search', function () {
it('should handle multiple occurrences of the pattern', function () {
const text = 'ABABABABABAB'
const pattern = 'ABAB'
const expected = [2, 4, 6, 8]
const expected = [0, 2, 4, 6, 8]

const result = rabinKarpSearch(text, pattern)
expect(result).to.deep.equal(expected)
Expand All @@ -27,4 +27,21 @@ describe('Rabin-Karp Search', function () {
const result = rabinKarpSearch(text, pattern)
expect(result).to.deep.equal(expected)
})

it('should find a pattern at the start of the text', function () {
expect(rabinKarpSearch('ABCABC', 'ABC')).to.deep.equal([0, 3])
expect(rabinKarpSearch('abc', 'a')).to.deep.equal([0])
expect(rabinKarpSearch('abc', 'abc')).to.deep.equal([0])
})

it('should find a long pattern', function () {
const pattern = 'abcdefghijkl'
expect(rabinKarpSearch(pattern + 'x' + pattern, pattern)).to.deep.equal([
0, 13
])
})

it('should return an empty array when the text is shorter than the pattern', function () {
expect(rabinKarpSearch('ab', 'abc')).to.deep.equal([])
})
})
Loading