Jeremy Kister wrote:
> I wrote a word descrambler that works very well, but is very slow
> compared to http://www.jumble.org
> 
> I'm wondering how others could write to code so that it'd find words
> faster.
> 
> #useful with dictionary from http://wordlist.sourceforge.net/
> 
> 
> use strict;
> 
> my %dictionary;
> opendir(DIR, "$ENV{'HOME'}/data/dictionary/");
> foreach my $file (grep {/^english-word/} readdir DIR){
>     open(DICT, "$ENV{'HOME'}/data/dictionary/$file");
>     warn "reading data/dictionary/$file\n";
>     while(<DICT>){
>         chop;
>         next unless(/^[a-z]+$/);
>         my $len = length($_);
>         push @{$dictionary{$len}}, $_;
>     }
>     close DICT;
> }
> closedir DIR;
> 
> while(1){
>     print "word: ";
>     chop(my $scramble = <STDIN>);
>     $scramble =~ s/\s+//g;
> 
>     my $slen = length($scramble);
>     my @s = split //, $scramble;
>     foreach my $word (@{$dictionary{$slen}}){
>         my @w = split //, $word;
>         my $found;
>         foreach my $sl (0..($slen-1)){
>             foreach my $l (0..($slen-1)){
>                 if($s[$sl] eq $w[$l]){
>                     delete $w[$l];
>                     $found++;
>                     last;
>                 }
>             }
>             last unless($found);
>         }
>         next unless($found == $slen);
>         print "$word\n";
>     }
> }

This runs a bit faster:

use warnings;
use strict;

my $dir = "$ENV{HOME}/data/dictionary";

opendir DIR, $dir or die "Cannot open '$dir' $!";

my %dictionary;
while ( my $file = readdir DIR ) {
    next unless /^english-word/;
    open DICT, '<', "$dir/$file" or die "Cannot open '$dir/$file' $!";
    warn "reading data/dictionary/$file\n";
    while ( <DICT> ) {
        chomp;
        next unless /^[a-z]+$/;
        push @{ $dictionary{ join '', sort /[a-z]/g } }, $_;
    }
    close DICT;
}
closedir DIR;

while ( 1 ) {
    print 'word: ';
    my $scramble = join '', sort <STDIN> =~ /[a-z]/g;

    print map "$_\n", @{ $dictionary{ $s } } if exists $dictionary{ $s }
}

__END__



John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to