Algoritmo Karp Rabin

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

function karp_rabin_matcher(T, P, b, q)

*--------------------------
local n, m
local d, h_y, h_x

b := if(valtype(b) # 'N', 256, b)


q := if(valtype(q) # 'N', 256, b)

/*
q = prime number
b = base
*/

n := length(T)
m := length(P)
if m > n
return "Error"
endif

d := b**(m-1) % q
h_y := 0
h_x := 0

#preprocessing
for i := 1 to m // asc?
h_y += (Int(substr(T, i - 1, 1)) * (b**(m - i )))
h_x += (Int(substr(P, i - 1, 1)) * (b**(m - i )))
next

h_y := h_y % q
h_x := h_x % q

for i := 0 to (n - m)
if h_y == h_x
if P == substr(T, i, i + m - 1)
qout("Pattern found:", i) // #MATCH
end
else
h_y = (h_y + b * q - Int(substr(T, i, 1)) * d) % q
h_y = (h_y * b + Int(substr(T, i + m, 1))) % q
i += 1
end
end
end

ej:
karp_rabin_matcher("hola quora!!", "quora", 256, 8355967)

You might also like