Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Add-A-Gram Performance

by tachyon (Chancellor)
on Feb 05, 2002 at 06:39 UTC ( [id://143368]=note: print w/replies, xml ) Need Help??


in reply to Add-A-Gram Performance

Running on an ancient PII 266 this takes less than a minute to process the standard unix dictionary. It uses a fairly efficient algorithm. Basically we bulid a hash which has the sorted letters of the words as its keys and the corresponding words (as an array ref) as its values. Thus we have a hash like:

... 'aet' => [ ate eat ] ...

As we have represented all the words as their sorted letters in a hash we make the search quick and easy. We work from the longest keys to the shortest and use recursion to test all the possibilities. We keep a list of 'winners' - any word which is in a winning list need not be tested again when we descend to it's level.

#!usr/bin/perl -w use strict; # get words into an array and a hash keyed on sorted letters open DICT, "c:/windows/desktop/unixdict.txt" or die "Oops $!\n"; my (%words,%winners); while(<DICT>) { chomp; my $sort = join '', (sort split'',$_); push @{$words{$sort}}, $_; } # test the words by length - longest first, don't repeat known winners for my $word (sort {length $b <=> length $a} keys %words) { defined $winners{$word} ? next : test($word); } sub test { my $word = $_[-1]; if (length $word <=3) { winner(@_); return; } my @letters = sort split '', $word; for my $i (0..$#letters) { my @temp = @letters; $temp[$i] = ''; my $short = join '', @temp; test(@_,$short) if exists $words{$short}; } } sub winner { local $, = " "; for (@_) { $winners{$_}++; print @{$words{$_}}, "\n"; } print "\n"; } __DATA__ planetarium manipulate aluminate laminate matinal animal manila milan main min [blah]

cheers

tachyon

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Log In?
Username:
Password:

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

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

      No recent polls found