How to resolve the algorithm Anagrams/Deranged anagrams step by step in the Picat programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Anagrams/Deranged anagrams step by step in the Picat programming language

Table of Contents

Problem Statement

Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Use the word list at unixdict to find and display the longest deranged anagram.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Anagrams/Deranged anagrams step by step in the Picat programming language

Source code in the picat programming language

go =>
  M = [W:W in read_file_lines("unixdict.txt")].group(sort),
  Deranged = [Value : _Key=Value in M, Value.length > 1, allderanged(Value)],
  MaxLen = max([V[1].length : V in Deranged]),
  println([V : V in Deranged, V[1].length==MaxLen]),
  nl.

% A and B are deranged: i.e. there is no
% position with the same character.
deranged(A,B) => 
   foreach(I in 1..A.length)
       A[I] != B[I]
   end.

% All words in list Value are deranged anagrams of each other.
allderanged(Value) => 
    IsDeranged = 1,
    foreach(V1 in Value, V2 in Value, V1 @< V2, IsDeranged = 1)
       if not deranged(V1,V2) then
          IsDeranged := 0
       end
    end,
    IsDeranged == 1.

% Groups the element in List according to the function F
group(List, F) = P, list(List) =>
   P = new_map(),
   foreach(E in List) 
      V = apply(F,E),
      P.put(V, P.get(V,[]) ++ [E])
   end.

  

You may also check:How to resolve the algorithm S-expressions step by step in the C++ programming language
You may also check:How to resolve the algorithm Find common directory path step by step in the Ring programming language
You may also check:How to resolve the algorithm Palindrome detection step by step in the Applesoft BASIC programming language
You may also check:How to resolve the algorithm Anti-primes step by step in the Pascal programming language
You may also check:How to resolve the algorithm Product of min and max prime factors step by step in the Cowgol programming language