THINK FIRST·CODE LATER

← All labs

Rabin–Karp: string search with a rolling hash

Problem

Write RabinKarp. The first line is a modulus p; the second line is the text; each following line is a pattern. For each pattern of length m compute its hash (c₀·31^(m−1) + c₁·31^(m−2) + … + c_(m−1)) mod p, then slide a window over the text, updating the window's hash in O(1) per step (remove the leading character, multiply by 31, add the new character). Whenever the hashes are equal, verify by comparing the characters.

Print the positions found, the number of windows, of hash matches and of spurious matches (equal hash, different text).

For the input

13
the quick brown fox jumps over the lazy dog
the
fox
cat

the program prints

"the" (hash 11): found at [0, 31]
  windows 41, hash matches 4, spurious 2
"fox" (hash 1): found at [16]
  windows 41, hash matches 4, spurious 3
"cat" (hash 8): found at []
  windows 41, hash matches 4, spurious 4

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d14-5-data-1.txt

13
the quick brown fox jumps over the lazy dog
the
fox
cat
What your program must print for d14-5-data-1.txt
"the" (hash 11): found at [0, 31]
  windows 41, hash matches 4, spurious 2
"fox" (hash 1): found at [16]
  windows 41, hash matches 4, spurious 3
"cat" (hash 8): found at []
  windows 41, hash matches 4, spurious 4

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d14-5-data-1.txt

Windows PowerShell does not understand <:

Get-Content d14-5-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.