Files
rose-ash/lib/ocaml/baseline/anagram_check.ml
giles 5c587c0f61
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
ocaml: phase 5.1 anagram_check.ml baseline (char-frequency array, 2/4 anagrams)
to_counts builds a 256-slot int array of character frequencies:

  let to_counts s =
    let counts = Array.make 256 0 in
    for i = 0 to String.length s - 1 do
      let c = Char.code s.[i] in
      counts.(c) <- counts.(c) + 1
    done;
    counts

same_counts compares two arrays element-by-element via for loop +
bool ref. is_anagram composes them.

Four pairs:
  listen ~ silent       true
  hello !~ world        false
  anagram ~ nagaram     true
  abc !~ abcd           false (length differs)
  sum                   2

Exercises Array.make + arr.(i) + arr.(i) <- v + nested for loops +
Char.code + s.[i].

57 baseline programs total.
2026-05-09 12:14:32 +00:00

24 lines
565 B
OCaml

let to_counts s =
let counts = Array.make 256 0 in
for i = 0 to String.length s - 1 do
let c = Char.code s.[i] in
counts.(c) <- counts.(c) + 1
done;
counts
let same_counts a b =
let result = ref true in
for i = 0 to 255 do
if a.(i) <> b.(i) then result := false
done;
!result
let is_anagram s t = same_counts (to_counts s) (to_counts t)
;;
(if is_anagram "listen" "silent" then 1 else 0) +
(if is_anagram "hello" "world" then 1 else 0) +
(if is_anagram "anagram" "nagaram" then 1 else 0) +
(if is_anagram "abc" "abcd" then 1 else 0)