How to resolve the algorithm Anagrams/Deranged anagrams step by step in the jq programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Anagrams/Deranged anagrams step by step in the jq 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 jq programming language
Source code in the jq programming language
# Input: an array of strings
# Output: a stream of arrays
def anagrams:
reduce .[] as $word (
{table: {}, max: 0}; # state
($word | explode | sort | implode) as $hash
| .table[$hash] += [ $word ]
| .max = ([ .max, ( .table[$hash] | length) ] | max ) )
| .table | .[] | select(length>1);
# Check whether the input and y are deranged,
# on the assumption that they are anagrams:
def deranged(y):
explode as $x # explode is fast
| (y | explode) as $y
| all( range(0;length); $x[.] != $y[.] );
# The task: loop through the anagrams,
# retaining only the best set of deranged anagrams so far.
split("\n") | select(length>0) # read all the words as an array
| reduce anagrams as $words ([]; # loop through all the anagrams
reduce $words[] as $v (.;
reduce ($words - [$v])[] as $w (.; # $v and $w are distinct members of $words
if $v|deranged($w)
then if length == 0 then [$v,$w]
elif ($v|length) == (.[0]|length) then . + [$v,$w]
elif ($v|length) > (.[0]|length) then [$v,$w]
else .
end
else .
end) ) )
| unique
You may also check:How to resolve the algorithm Loops/Infinite step by step in the FALSE programming language
You may also check:How to resolve the algorithm Radical of an integer step by step in the RPL programming language
You may also check:How to resolve the algorithm Strip block comments step by step in the Java programming language
You may also check:How to resolve the algorithm Undefined values step by step in the Prolog programming language
You may also check:How to resolve the algorithm Enumerations step by step in the jq programming language