The Weekly Challenge 005

Anagrams and Sequence Fun!

Original | My Solutions

Task 1: All anagrams for a word

"The Word Mixer: When Letters Dance!"

Write a program which prints out all anagrams for a given word.

Perl
#!/usr/bin/perl
use strict;
use warnings;

sub print_anagrams {
    my $word = shift;
    my %freq; $freq{$_}++ for split //, $word;

    sub gen {
        my ($prefix, $freq_ref) = @_;
        if (length $prefix == length $word) { print "$prefix\n"; return; }
        for my $letter (keys %$freq_ref) {
            if ($freq_ref->{$letter} > 0) {
                $freq_ref->{$letter}--;
                gen($prefix . $letter, $freq_ref);
                $freq_ref->{$letter}++;
            }
        }
    }
    gen("", \%freq);
}

print_anagrams("hello");
print_anagrams("pear");
Python
#!/usr/bin/env python
import itertools

def get_anagrams(word: str) -> set:
    return set("".join(p) for p in itertools.permutations(word))

print(get_anagrams("hello"))
print(get_anagrams("pear"))

Task 2: Sequence with most anagrams

"The Anagram Champion!"

Find the sequence of characters that has the most anagrams.

Perl
#!/usr/bin/perl
use strict;
use warnings;

sub find_most_anagrams {
    my ($str) = @_;
    my %anagrams;
    for my $i (0..length($str)-1) {
        for my $j ($i+1..length($str)) {
            my $sub = substr($str, $i, $j-$i);
            push @{$anagrams{join("", sort split//, $sub)}}, $sub;
        }
    }
    my ($max) = sort {$#{$$a[0]} <=> $#{$$b[0]}} values %anagrams;
    return $max->[0];
}
Python
#!/usr/bin/env python
import itertools

def most_anagrams(string):
    best = ""
    for i in range(1, len(string)+1):
        for j in range(i):
            sub = string[j:i]
            count = len(set("".join(p) for p in itertools.permutations(sub)))
            if not best or count > len(set("".join(p) for p in itertools.permutations(best))):
                best = sub
    return best