Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 21s
Knuth-Morris-Pratt linear-time string search: - kmp_table builds failure function in O(|pattern|) - kmp_search scans text once in O(|text|), counting matches - After a hit, k := t.(n-1) so overlapping matches still count kmp_search "abababcabababcababcc" "abab" = 5 Hits at positions 0, 2, 7, 9, 14 (overlapping at 0/2 and 7/9). Tests: nested while-inside-for, char inequality (.<>), pat.[i] string indexing, Array.make 0, combined string + array indexing. 140 baseline programs total.
38 lines
782 B
OCaml
38 lines
782 B
OCaml
let kmp_table pat =
|
|
let n = String.length pat in
|
|
let t = Array.make n 0 in
|
|
let k = ref 0 in
|
|
for i = 1 to n - 1 do
|
|
while !k > 0 && pat.[!k] <> pat.[i] do
|
|
k := t.(!k - 1)
|
|
done;
|
|
if pat.[!k] = pat.[i] then k := !k + 1;
|
|
t.(i) <- !k
|
|
done;
|
|
t
|
|
|
|
let kmp_search text pat =
|
|
let m = String.length text in
|
|
let n = String.length pat in
|
|
if n = 0 then 0
|
|
else begin
|
|
let t = kmp_table pat in
|
|
let count = ref 0 in
|
|
let k = ref 0 in
|
|
for i = 0 to m - 1 do
|
|
while !k > 0 && pat.[!k] <> text.[i] do
|
|
k := t.(!k - 1)
|
|
done;
|
|
if pat.[!k] = text.[i] then k := !k + 1;
|
|
if !k = n then begin
|
|
count := !count + 1;
|
|
k := t.(n - 1)
|
|
end
|
|
done;
|
|
!count
|
|
end
|
|
|
|
;;
|
|
|
|
kmp_search "abababcabababcababcc" "abab"
|