How to resolve the algorithm Anagrams step by step in the OCaml programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Anagrams step by step in the OCaml programming language

Table of Contents

Problem Statement

When two or more words are composed of the same characters, but in a different order, they are called anagrams. Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Anagrams step by step in the OCaml programming language

Source code in the ocaml programming language

let explode str =
  let l = ref [] in
  let n = String.length str in
  for i = n - 1 downto 0 do
    l := str.[i] :: !l
  done;
  (!l)

let implode li =
  let n = List.length li in
  let s = String.create n in
  let i = ref 0 in
  List.iter (fun c -> s.[!i] <- c; incr i) li;
  (s)

let () =
  let h = Hashtbl.create 3571 in
  let ic = open_in "unixdict.txt" in
  try while true do
    let w = input_line ic in
    let k = implode (List.sort compare (explode w)) in
    let l =
      try Hashtbl.find h k
      with Not_found -> [] 
    in
    Hashtbl.replace h k (w::l);
  done with End_of_file -> ();
  let n = Hashtbl.fold (fun _ lw n -> max n (List.length lw)) h 0 in
  Hashtbl.iter (fun _ lw ->
    if List.length lw >= n then
    ( List.iter (Printf.printf " %s") lw;
      print_newline () )
  ) h


  

You may also check:How to resolve the algorithm FizzBuzz step by step in the Asymptote programming language
You may also check:How to resolve the algorithm Sequence of non-squares step by step in the Delphi programming language
You may also check:How to resolve the algorithm Lucas-Lehmer test step by step in the Modula-3 programming language
You may also check:How to resolve the algorithm Multiplicative order step by step in the REXX programming language
You may also check:How to resolve the algorithm World Cup group stage step by step in the Scala programming language