ocaml: phase 5.1 count_palindromes.ml baseline ("aabaa" -> 9 palindromes)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 25s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 25s
Expand-around-center linear-time palindrome counting:
for c = 0 to 2*n - 2 do
let l = ref (c / 2) in
let r = ref ((c + 1) / 2) in
while !l >= 0 && !r < n && s.[!l] = s.[!r] do
count := !count + 1; l := !l - 1; r := !r + 1
done
done
The 2n-1 centers cover both odd (c even -> l = r) and even
(c odd -> l = r - 1) palindromes.
For "aabaa":
5 singletons + 2 "aa" + 1 "aba" + 1 "aabaa" = 9
Complements lps_dp.ml (longest subsequence) and manacher.ml
(longest substring); this one *counts* all palindromic substrings.
187 baseline programs total.
This commit is contained in:
17
lib/ocaml/baseline/count_palindromes.ml
Normal file
17
lib/ocaml/baseline/count_palindromes.ml
Normal file
@@ -0,0 +1,17 @@
|
||||
let count_pal s =
|
||||
let n = String.length s in
|
||||
let count = ref 0 in
|
||||
for c = 0 to 2 * n - 2 do
|
||||
let l = ref (c / 2) in
|
||||
let r = ref ((c + 1) / 2) in
|
||||
while !l >= 0 && !r < n && s.[!l] = s.[!r] do
|
||||
count := !count + 1;
|
||||
l := !l - 1;
|
||||
r := !r + 1
|
||||
done
|
||||
done;
|
||||
!count
|
||||
|
||||
;;
|
||||
|
||||
count_pal "aabaa"
|
||||
@@ -32,6 +32,7 @@
|
||||
"coin_min.ml": 6,
|
||||
"count_change.ml": 406,
|
||||
"count_inversions.ml": 12,
|
||||
"count_palindromes.ml": 9,
|
||||
"count_subarrays_k.ml": 7,
|
||||
"csv.ml": 10,
|
||||
"egg_drop.ml": 8,
|
||||
|
||||
@@ -407,6 +407,15 @@ _Newest first._
|
||||
binary search tree (`type 'a tree = Leaf | Node of 'a * 'a tree *
|
||||
'a tree`) with insert + in-order traversal. Tests parametric ADT,
|
||||
recursive match, List.append, List.fold_left.
|
||||
- 2026-05-11 Phase 5.1 — count_palindromes.ml baseline (count
|
||||
palindromic substrings of "aabaa" = 9). Expand-around-center
|
||||
with 2n−1 centers (n odd-length, n−1 even-length); for each,
|
||||
walk outward while characters match and both indices in range.
|
||||
Decomposition: c/2 and (c+1)/2 gives both odd (c even) and even
|
||||
(c odd) starting pairs. Palindromes in "aabaa": 5 singletons
|
||||
+ 2 "aa"s + 1 "aba" + 1 "aabaa" = 9. Complements lps_dp.ml
|
||||
(longest subsequence) and manacher.ml (longest substring); this
|
||||
one counts ALL palindromic substrings. 187 baseline programs total.
|
||||
- 2026-05-11 Phase 5.1 — count_subarrays_k.ml baseline (count
|
||||
contiguous subarrays of [1;1;1;2;-1;3;1;-2;4] summing to k=3
|
||||
= 7). Prefix-sum brute force in O(n²): build cumulative array,
|
||||
|
||||
Reference in New Issue
Block a user