#!/usr/bin/ruby

# Translation of: https://rosettacode.org/wiki/Anagrams/Deranged_anagrams#Perl

func find_deranged (a) {

    var r = ^a

    r.each { |i|
        with(r.from(i+1).first_by { |j| !(a[i] `overlaps` a[j]) }) { |j|
            "length %d: %s => %s\n".printf(a[i].len, a[i], a[j]);
            return true;
        }
    }

    return false;
}

func main () {

    var lwp = (
        try   { frequire('LWP::Simple') }
        catch { warn("** LWP::Simple is not installed!"); return() }
    )

    "** Retrieving the wordlist...".say;
    var words = lwp.get('https://web.archive.org/web/20180611003215if_/http://www.puzzlers.org:80/pub/wordlists/unixdict.txt').words;
    "** Processing the words...".say;

    var time = Time.micro;
    var letter_list = Hash();

    # Store anagrams in hash table by letters they contain
    words.each { |word|
        letter_list{word.sort} := [] -> append(word);
    }

    "** The hashing took %.5f seconds!\n".printf(Time.micro - time);

    letter_list.keys                        \
         .grep {|k| letter_list{k}.len > 1} \      # take only ones with anagrams
         .sort_by {|a| -a.len }             \      # sort by length, descending
         .each {|key|

        # if we find a pair, they are the longest due to the sort before
        find_deranged(letter_list{key}) && (
            "** The process took %.5f seconds!\n".printf(Time.micro - time);
            break;
        );
    }
}

main();