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.

Task[edit]
Use the word list at unixdict to find and display the longest deranged anagram.



Related tasks
 Permutations/Derangements
 Best shuffle
Word plays

Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams





Other tasks related to string operations:

Metrics
 Array length
 String length
 Copy a string
 Empty string  (assignment)
Counting
 Word frequency
 Letter frequency
 Jewels and stones
 I before E except after C
 Bioinformatics/base count
 Count occurrences of a substring
 Count how many vowels and consonants occur in a string
Remove/replace
 XXXX redacted
 Conjugate a Latin verb
 Remove vowels from a string
 String interpolation (included)
 Strip block comments
 Strip comments from a string
 Strip a set of characters from a string
 Strip whitespace from a string -- top and tail
 Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
 Word wheel
 ABC problem
 Sattolo cycle
 Knuth shuffle
 Ordered words
 Superpermutation minimisation
 Textonyms (using a phone text pad)
 Anagrams
 Anagrams/Deranged anagrams
 Permutations/Derangements
Find/Search/Determine
 ABC words
 Odd words
 Word ladder
 Semordnilap
 Word search
 Wordiff  (game)
 String matching
 Tea cup rim text
 Alternade words
 Changeable words
 State name puzzle
 String comparison
 Unique characters
 Unique characters in each string
 Extract file extension
 Levenshtein distance
 Palindrome detection
 Common list elements
 Longest common suffix
 Longest common prefix
 Compare a list of strings 
 Longest common substring
 Find common directory path
 Words from neighbour ones
 Change e letters to i in words
 Non-continuous subsequences
 Longest common subsequence
 Longest palindromic substrings
 Longest increasing subsequence
 Words containing "the" substring
 Sum of the digits of n is substring of n
 Determine if a string is numeric
 Determine if a string is collapsible
 Determine if a string is squeezable
 Determine if a string has all unique characters
 Determine if a string has all the same characters
 Longest substrings without repeating characters
 Find words which contains all the vowels
 Find words which contains most consonants
 Find words which contains more than 3 vowels
 Find words which first and last three letters are equals
 Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
 Substring
 Rep-string
 Word wrap
 String case
 Align columns
 Literals/String
 Repeat a string
 Brace expansion
 Brace expansion using ranges
 Reverse a string
 Phrase reversals
 Comma quibbling
 Special characters
 String concatenation
 Substring/Top and tail
 Commatizing numbers
 Reverse words in a string
 Suffixation of decimal numbers
 Long literals, with continuations 
 Numerical and alphabetical suffixes
 Abbreviations, easy
 Abbreviations, simple
 Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
 Mad Libs
 Magic 8-ball
 99 Bottles of Beer
 The Name Game (a song)
 The Old lady swallowed a fly
 The Twelve Days of Christmas
Tokenize
 Text between
 Tokenize a string
 Word break problem
 Tokenize a string with escaping
 Split a character string based on change of character
Sequences
 Show ASCII table
 De Bruijn sequences
 Self-referential sequences
 Generate lower case ASCII alphabet




# find the largest deranged anagrams in a list of words              #
# use the associative array in the Associate array/iteration task    #
PR read "aArray.a68" PR
 
# returns the length of str                                          #
OP LENGTH = ( STRING str )INT: 1 + ( UPB str - LWB str );
 
# returns TRUE if a and b are the same length and have no            #
# identical characters at any position,                              #
# FALSE otherwise                                                    #
PRIO ALLDIFFER = 9;
OP   ALLDIFFER = ( STRING a, b )BOOL:
     IF LENGTH a /= LENGTH b
     THEN
        # the two stringa are not the same size                      #
        FALSE
     ELSE
        # the strings are the same length, check the characters      #
        BOOL result := TRUE;
        INT  b pos  := LWB b;
        FOR a pos FROM LWB a TO UPB a WHILE result := ( a[ a pos ] /= b[ b pos ] )
        DO
            b pos +:= 1
        OD;
        result
     FI # ALLDIFFER # ;
 
# returns text with the characters sorted                            #
OP   SORT = ( STRING text )STRING:
     BEGIN
        STRING sorted := text;
        FOR end pos FROM UPB sorted - 1 BY -1 TO LWB sorted
        WHILE
            BOOL swapped := FALSE;
            FOR pos FROM LWB sorted TO end pos DO
                IF sorted[ pos ] > sorted[ pos + 1 ]
                THEN              
                    CHAR  t           := sorted[ pos     ];
                    sorted[ pos     ] := sorted[ pos + 1 ];
                    sorted[ pos + 1 ] := t;
                    swapped           := TRUE
                FI
            OD;
            swapped
        DO SKIP OD;
        sorted
     END # SORTED # ;
 
# read the list of words and find the longest deranged anagrams      #
 
CHAR separator = "|"; # character that will separate the anagrams    #
 
IF  FILE input file;
    STRING file name = "unixdict.txt";
    open( input file, file name, stand in channel ) /= 0
THEN
    # failed to open the file #
    print( ( "Unable to open """ + file name + """", newline ) )
ELSE
    # file opened OK #
    BOOL at eof := FALSE;
    # set the EOF handler for the file #
    on logical file end( input file, ( REF FILE f )BOOL:
                                     BEGIN
                                         # note that we reached EOF on the #
                                         # latest read #
                                         at eof := TRUE;
                                         # return TRUE so processing can continue #
                                         TRUE
                                     END
                       );
    REF AARRAY words := INIT LOC AARRAY;
    STRING word;
    INT    longest derangement := 0;
    STRING longest word        := "<none>";
    STRING longest anagram     := "<none>";
    WHILE NOT at eof
    DO
        STRING word;
        get( input file, ( word, newline ) );
        INT    word length = LENGTH word;
        IF  word length >= longest derangement
        THEN
            # this word is at least long as the longest derangement   #
            # found so far - test it                                  #
            STRING sorted word = SORT word;
            IF ( words // sorted word ) /= ""
            THEN
                # we already have this sorted word - test for         #
                # deranged anagrams                                   #
                # the word list will have a leading separator         #
                # and be followed by one or more words separated by   #
                # the separator                                       #
                STRING word list   := words // sorted word;
                INT    list pos    := LWB word list + 1;
                INT    list max     = UPB word list;
                BOOL   is deranged := FALSE;
                WHILE  list pos < list max
                  AND  NOT is deranged
                DO
                    STRING anagram = word list[ list pos : ( list pos + word length ) - 1 ];
                    IF  is deranged := word ALLDIFFER anagram
                    THEN
                        # have a deranged anagram                     #
                        longest derangement := word length;
                        longest word        := word;
                        longest anagram     := anagram
                    FI;            
                    list pos +:= word length + 1
                OD
            FI;
            # add the word to the anagram list                        #
            words // sorted word +:= separator + word
        FI
    OD;
    close( input file );
    print( ( "Longest deranged anagrams: "
           , longest word
           , " and "
           , longest anagram
           , newline
           )
         )
FI