Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 47s
Group anagrams by canonical (sorted-chars) key using Hashtbl + List.sort. Demonstrates char-by-char traversal via String.get + for-loop + ref accumulator + Hashtbl as a multi-valued counter.
27 lines
690 B
OCaml
27 lines
690 B
OCaml
(* Baseline: count anagram groups using Hashtbl + sort *)
|
|
|
|
(* Sort the chars in a string to get its anagram-equivalence key *)
|
|
let canonical s =
|
|
let n = String.length s in
|
|
let chars = ref [] in
|
|
for i = 0 to n - 1 do
|
|
chars := (String.get s i) :: !chars
|
|
done ;
|
|
let sorted = List.sort compare !chars in
|
|
String.concat "" sorted
|
|
;;
|
|
|
|
let count_groups words =
|
|
let counts = Hashtbl.create 16 in
|
|
List.iter
|
|
(fun w ->
|
|
let k = canonical w in
|
|
match Hashtbl.find_opt counts k with
|
|
| None -> Hashtbl.add counts k 1
|
|
| Some n -> Hashtbl.replace counts k (n + 1))
|
|
words ;
|
|
Hashtbl.length counts
|
|
;;
|
|
|
|
count_groups ["eat"; "tea"; "tan"; "ate"; "nat"; "bat"]
|