Well, it certainly takes a while to build the db the first time... (over 15 mins so far... maybe LevenshteinXS isn't quite right on Win?) Here's my offing that was written for clarity, rather than efficiency. Then again, maybe I'll say it's optimized for startup time, rather than solution time... who likes those long 'loading...' screens, anyway?
Update:I should have realized that I'm using the yawl-0.3.2 word list, and the time to build the db is probably affected by that!
use strict;
use warnings;
use List::Compare;
use Benchmark qw( cmpthese );
my $lword = shift || 'love';
my $rword = shift || 'hate';
die unless length($rword) == length($lword);
my $length = length($lword);
my $wordlist;
open(FH,'word.list') or die;
while(<FH>) {
chomp;
undef($wordlist->{lc $_}) if length($_) == $length;
}
print solo($lword,$rword);
#cmpthese( ... );
sub solo {
my ( $rdepth,$ldepth,$rex,$lex ) = (0,0,1,1);
my $left = { $_[0] => [$_[0]] };
my $right = { $_[1] => [$_[1]] };
while ( 1 ) {
# compare the intersection of the leaf nodes
my $lc = List::Compare->new( {
lists => [ [keys %$left], [keys %$right] ],
accelerated => 1,
unsorted => 1,
} );
my @int = $lc->get_intersection();
if ( @int ) {
my $solve = shift @int;
pop @{$right->{$solve}};
return join("\n", @{$left->{$solve}}, reverse @{$right->{$
+solve}}) . "\n";
}
# pick a side to expand the search in
if ( $lex && $rdepth > $ldepth ) {
$lex = expandTree($left,++$ldepth);
}
elsif ( $rex ) {
$rex = expandTree($right,++$rdepth);
}
else {
return "No solution.";
}
}
}
sub expandTree {
my ($tree, $depth) = @_;
my ($word, $path, $expanded);
while ( ($word, $path) = each %$tree ) {
if ( @$path == $depth ) {
for my $i (0..(length($word)-1) ) {
for my $letter ( 'a'..'z' ) {
my $try = $word;
substr($try,$i,1) = $letter;
next if exists $tree->{$try};
if ( exists $wordlist->{$try} ) {
$tree->{$try} = [ @{$tree->{$word}}, $try ];
$expanded = 1;
}
}
}
}
}
return $expanded;
}
--Solo
--
You said you wanted to be around when I made a mistake; well, this could be it, sweetheart.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.