Complete the code to calculate the initial hash of the pattern.
let mut pattern_hash = 0u64; for &byte in pattern.as_bytes() { pattern_hash = (pattern_hash * base + [1] as u64) % modulus; }
The hash is calculated by adding the byte value of each character in the pattern.
Complete the code to update the rolling hash when sliding the window.
text_hash = (text_hash + modulus - (old_char as u64 * high_base) % modulus) % modulus; text_hash = (text_hash * base + [1] as u64) % modulus;
When sliding the window, add the new character's byte to the rolling hash.
Fix the error in the hash comparison condition to check for a match.
if text_hash == [1] && &text[i..i+pattern_len] == pattern { result.push(i); }
The rolling hash of the current text window should be compared to the pattern's hash.
Fill both blanks to compute the highest base power for rolling hash.
let mut high_base = 1u64; for _ in 1..[1] { high_base = (high_base * [2]) % modulus; }
high_base is base raised to the power of pattern length minus one, modulo modulus.
Fill all three blanks to complete the Rabin-Karp search function.
fn rabin_karp_search(text: &str, pattern: &str) -> Vec<usize> {
let base = 256u64;
let modulus = 101u64;
let pattern_len = pattern.len();
let text_len = text.len();
if pattern_len > text_len {
return vec![];
}
let mut pattern_hash = 0u64;
let mut text_hash = 0u64;
let mut high_base = 1u64;
for _ in 1..pattern_len {
high_base = (high_base * [1]) % modulus;
}
for i in 0..pattern_len {
pattern_hash = (pattern_hash * [2] + pattern.as_bytes()[i] as u64) % modulus;
text_hash = (text_hash * [2] + text.as_bytes()[i] as u64) % modulus;
}
let mut result = Vec::new();
for i in 0..=text_len - pattern_len {
if text_hash == pattern_hash && &text[i..i+pattern_len] == pattern {
result.push(i);
}
if i < text_len - pattern_len {
text_hash = (text_hash + modulus - (text.as_bytes()[i] as u64 * high_base) % modulus) % modulus;
text_hash = (text_hash * [3] + text.as_bytes()[i + pattern_len] as u64) % modulus;
}
}
result
}The base is used for power calculation and hash updates. modulus is used only for modulo operations.
