Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: OT: How to find anagrams?

by pizza_milkshake (Monk)
on Apr 28, 2004 at 02:58 UTC ( [id://348696]=note: print w/replies, xml ) Need Help??


in reply to OT: How to find anagrams?

not the prettiest code i've ever written, but it seems to do the trick.
#!perl -wl use strict; $_ = shift @ARGV || "CLEANSE"; our (%kw, %words); my ($match, @matches); my $future = {"" => ""}; sub sortword { return join("", sort pop=~/./g) } sub dissect { my %h; map $h{$_}++, split(//,pop); return \%h } sub scrub { # make sure a word isn't longer than our # kw or has chars kw doesn't my $w = shift @_; return 0 if length($w) > $kw{"len"}; my $d = dissect($w); map { return 0 if !defined($kw{"d"}->{$_}) || $kw{"d"}->{$_} < $d->{$_} } keys %$d; return 1; } sub process { # run one iteration through %words my ($cand, @match, %future) = @_; for my $w (keys %words) { for my $c (keys %$cand) { my $len = length($cand->{$c}) + $words{$w}; next if $len > $kw{"len"}; my $nk = "$c:$w"; $future{$nk} = sortword($cand->{$c} . $w); if ($len == $kw{"len"}) { push @match, $nk if $future{$nk} eq $kw{"kw"}; delete $future{$nk}; } } } return (\@match, \%future); } %kw = ( "word" => $_ ,"len" => length($_) ,"kw" => sortword($_) ,"d" => dissect($_) ); map { chomp; $words{$_} = length() if scrub($_); } <DATA>; while (keys %$future) { ($match, $future) = process($future); push @matches, @$match; } print "anagrams for " . $kw{"word"} . ":"; map print, @matches; __DATA__ SEE SCALENE CLAN EEL BOB PIZZA SCAN MONKS PERL

perl -e'$_="nwdd\x7F^n\x7Flm{{llql0}qs\x14";s/./chr(ord$&^30)/ge;print'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://348696]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (1)
As of 2024-04-25 01:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found