Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

Generate Multi-word Anagrams

by kvale (Monsignor)
on Apr 28, 2004 at 01:58 UTC ( #348681=CUFP: print w/replies, xml ) Need Help??

This program, inspired by OT: How to find anagrams?, computes multi-word anagrams of a word or phrase. The program works by first creating a pool of possible words that could be made from the letters of the phrase. Then it enumerates over all possible combinations of word lengths, which corresponds to all the integer partitions of the phrase length. For each partition, it then tests all possible words of those particular lengths to see if they form an anagram of the phrase. For example, the phrase 'scalene' produces 'cleanse' and 'lee scan', among others. Output is one anagram per line.
#!/usr/bin/perl # usage: anagram 'my phrase' dictionary_file use warnings; use strict; use Algorithm::Loops qw/ NestedLoops /; my $phrase = shift; my $dict = shift; # collapse all letters into a sorted sequence (my $sorted = $phrase) =~ s/[\W]//g; $sorted = join '', sort split //, $sorted; my $rx = qr|^[$sorted]+$|i; my $phrase_length = length $sorted; open DICT, "<$dict" or die "Could not open $dict: $!\n"; my @list; my $num_words; while (my $word = <DICT>) { chomp $word; next if length $word > $phrase_length; next unless $word =~ $rx; next if length $word == 1 && $word ne 'a' && $word ne 'i'; push @{ $list[length $word] }, $word; $num_words++; } close DICT; print "Number of words in pool: $num_words\n"; my @size; $size[$_] = @{ $list[ $_ ] } for 1..$phrase_length; # Enumerate over all integer partitions my @p; part( 2*$phrase_length, $phrase_length, 0); ### Subroutines sub part { my ($n, $k, $t) = @_; $p[$t] = $k; check_part( $t) if $n == $k; for (my $j = $k<$n-$k ? $k : $n-$k; $j >= 1; $j--) { part( $n-$k, $j, $t+1); } } my %ana_seen; sub check_part { my $t = shift; # create iterator for all combos of words my @iter = map { [0..$size[$p[$_]]-1] } 1..$t; my $iter = NestedLoops( \@iter); while( my @i = $iter->() ) { my $formatted = join " ", sort map {$list[ $p[$_] ][ $i[$_-1] ]} + 1..$t; next if $ana_seen{$formatted}; $ana_seen{$formatted} = 1; my $test = join "", split / /, $formatted; $test = join '', sort split //, $test; print "$formatted\n" if $test eq $sorted; } }
Update: cleaned up check_part() - removed debugging, filtered dups.


Replies are listed 'Best First'.
Re: Generate Multi-word Anagrams
by japhy (Canon) on Apr 28, 2004 at 08:27 UTC
    I devised an algorithm where a string is turned into a 26-byte representation of itself, where each byte indicates how many occurrences of a given character are found in the string. For example:
    $s = "antidisestablishmentarianism"; # a b c d e f g h i j k l m n o p q r s t u v w x y z $r = "\4\1\0\1\2\0\0\1\5\0\0\1\2\3\0\0\0\1\4\3\0\0\0\0\0\0"
    That is then turned into a regex (so \4 becomes [\0-\4]). Then I match the representation of another string against that regex.

    I can post the code if you'd like.

    Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a job (NYC-area)
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;
(Golf) Generate Multi-word Anagrams
by dragonchild (Archbishop) on Apr 28, 2004 at 20:12 UTC
    A golfed version that passes strictures w/o warnings ... Comes in at 362 characters and requires a little preprocessing of the dictionary to organize by length.

    I could have reduced it further by removing the check to make sure that letters exist, but it wouldn't run in reasonable time otherwise.

    use Algorithm::Loops qw( NestedLoops ); sub a { # 1 2 3 4 5 6 7 + 8 #234567890123456789012345678901234567890123456789012345678901234567890 +1234567890 my$w=shift;my@x=sort$w=~/\w/g;my@d=@_;my$i=sub{$^=pop;my$i=NestedLoops +([map{my$x=$d[$@[$_]];[grep{$x->[$_]!~/[^$w]/}0..$#{$x}]}1..$^ ]);whi +le(@%=&$i){my@f=sort map{$d[$@[$_]][$%[$_-1]]}1..$^;$.[@.]="@f"if"@{[ +sort map{/./g}@f]}"eq"@x"}};my$p;$p=sub{my($n,$k,$t)=@_;$@[$t]=$k;$n- +$k?map{$p->($n-$k,$_,$t+1)}reverse 1..(2*$k<$n?$k:$n-$k):&$i($t)};&$p +(2*@x,1*@x,0);@. } open (my $dict, "/usr/dict/words") || die "No words\n"; my @dict; push @{$dict[length $_]}, $_ for grep { length > 1 || $_ eq 'a' || $_ eq 'i' } grep { lc eq $_ } grep { chomp } <$dict>; close ($dict); print "$_\n" for a( 'together', @dict);

    Update: Added code to remove dupes. Up to 378 characters. *sighs*

    my$w=shift;my@x=sort$w=~/\w/g;my@d=@_;my%s;my$i=sub{$%=pop;my$i=Nested +Loops([map{my$x=$d[$@[$_]];[grep{$x->[$_]!~/[^$w]/}0..$#$x]}1..$%]);w +hile(@%=&$i){my@f=sort map{$d[$@[$_]][$%[$_-1]]}1..$%;$.[@.]="@f"if!$ +s{"@f"}++&&"@{[sort map{/./g}@f]}"eq"@x"}};my $p;$p=sub{my($n,$k,$t)= +@_;$@[$t]=$k;$n-$k?map{$p->($n-$k,$_,$t+1)}reverse 1..(2*$k<$n?$k:$n- +$k):&$i($t)};&$p(2*@x,1*@x,0);@.

    Update2: Cleaned things up a little. Down to 348 characters! :-)

    my($w,@d)=@_;my@x=sort$w=~/\w/g;**=sub{$%=pop;*)=NestedLoops([map{my$x +=$d[$@[$_]];[grep{$x->[$_]!~/[^$w]/}0..$#$x]}1..$%]);while(@%=&)){my@ +f=sort map{$d[$@[$_]][$%[$_-1]]}1..$%;$.[@.]="@f"if!$_{"@f"}++&&"@{[s +ort map{/./g}@f]}"eq"@x"}};*(=sub{my($n,$k,$t)=@_;$@[$t]=$k;$n-$k?map +{&(($n-$k,0-$_,$t+1)}(2*$k<$n?-$k:$k-$n)..-1:&*($t)};&((2*@x,1*@x,0); +@.

    Update3: Took advantage of NestedLoops() callback methods. 336 characters! I'm closing in on 320 ...

    my($w,@d)=@_;my@x=sort$w=~/\w/g;**=sub{$%=pop;*)=NestedLoops([map{my$x +=$d[$@[$_]];[grep{$x->[$_]!~/[^$w]/}0..$#$x]}1..$%],sub{my@f=sort map +$d[$@[$_]][$_[$_-1]],1..$%;$.[@.]="@f"if!$_{"@f"}++&&"@{[sort map/./g +,@f]}"eq"@x"})};*(=sub{my($n,$k,$t)=@_;$@[$t]=$k;$n-$k?map&(($n-$k,0- +$_,$t+1),(2*$k<$n?-$k:$k-$n)..-1:&*($t)};&((2*@x,1*@x,0);@.

    Update4: 319!! Woo-hoo!

    ($,,@,)=@_;@$=sort$,=~/\w/g;**=sub{@%=1..pop;NestedLoops([map{$a=$,[$@ +[$_]];[grep{$$a[$_]!~/[^$,]/}0..$#$a]}@%],sub{@:=sort map$,[$@[$_]][$ +_[$_-1]],@%;$.[@.]="@:"if!$_{"@:"}++&&"@{[sort map/./g,@:]}"eq"@$"})} +;*(=sub{my($n,$k,$t)=@_;$@[$t]=$k;($n-=$k)>0?map&(($n,0-$_,$t+1),($k< +$n?-$k:-$n)..-1:&*($t)};&((2*@$,1*@$,0);@.

    Update5: Hunting for 300 ... at 305 right now:

    ($,,@,)=@_;@$=sort$,=~/\w/g;*(=sub{my($n,$k,$t)=@_;$@[$t]=$k;($n-=$k)> +0?map&(($n,0-$_,$t+1),($k<$n?-$k:-$n)..-1:(@%=1..$t),NestedLoops([map +{$a=$,[$@[$_]];[grep{$$a[$_]!~/[^$,]/}0..$#$a]}@%],sub{@:=sort map$,[ +$@[$_]][$_[$_-1]],@%;$.[@.]="@:"if!$_{"@:"}++&&"@{[sort map/./g,@:]}" +eq"@$"})};&((2*@$,1*@$,0);@.

    Update6: I'm happy. 297 characters, but no longer warnings-safe.

    ($,,@,)=@_;@$=sort$,=~/\w/g;*b=sub{my($n,$k,$t)=@_;$@[$t]=$k;($n-=$k)> +0?map b($n,0-$_,$t+1),($k<$n?-$k:-$n)..-1:(@%=@,[@@[1..$t]]),NestedLo +ops([map{$a=$_;[grep$$a[$_]!~/[^$,]/,0..$#$a]}@%],sub{@:=sort map$%[$ +_][pop],1-@%..0;$.[@.]="@:"if!$_{"@:"}++&&"@{[sort map/./g,@:]}"eq"@$ +"})};b(2*@$,1*@$);@.

    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

Re: Generate Multi-word Anagrams
by dragonchild (Archbishop) on Apr 28, 2004 at 02:18 UTC
    On first blush, this looks like it wouldn't find the fact that "together" has "to", "get", and "her" as a multi-word anagram ...

    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

      If you run the program, you will find
      her get to
      as one of the solutions. What caused the blush?


Re: Generate Multi-word Anagrams
by QM (Parson) on Jan 25, 2005 at 22:36 UTC
    I noticed this lines gives an error when there are no words of a given length:
    $size[$_] = @{ $list[ $_ ] } for 1..$phrase_length;
    The error is:
    Can't use an undefined value as an ARRAY reference at line +34.
    I fixed it with this:
    for my $length ( 1..$phrase_length ) { my $ref = ref $list[ $length ]; $size[$length] = ( $ref =~ /ARRAY/ ? @{ $list[ $length ] } : 0 ); }
    (I didn't find an easier way, though I didn't look too hard.)

    I'd be interested in seeing any improvements you (or anyone else) has made to this offline.

    Quantum Mechanics: The dreams stuff is made of

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: CUFP [id://348681]
Approved by davido
[Cosmic37]: you are right $mydt did not contain what I expected... :-D I will now think :-D
[Cosmic37]: crunch...grind... whirr...gnashing metal crunching cogs...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (9)
As of 2017-06-29 17:06 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (673 votes). Check out past polls.