Not a module, and not OO, but a working solution:
#!perl -l
use strict;
use warnings;
sub sort_word {
return join '', sort split //, $_[0];
}
my %hints = (
bumps => 2,
seams => 2,
domes => 3,
shake => 3,
pokes => 3,
dukes => 3
);
my $wordlen = 5;
my %dict;
open(DICT, '/usr/dict/words') or die "$!: /usr/dict/words\n";
chomp, push @{$dict{sort_word($_)}}, $_ while (<DICT>);
close(DICT);
my $guess = 'a' x $wordlen;
sub letters_in_common {
my ($str1, $str2) = @_;
my %u = map {$_ => $_} split //, $str1;
return scalar(grep defined, delete @u{split //, $str2});
}
while (length($guess) == $wordlen) {
# Check criteria
my $match = 1;
while (my ($k,$v) = each %hints) {
if (letters_in_common($guess, $k) != $v) {
$match = 0;
keys %hints; # Reset each
last;
}
}
# If match, check dictionary and print results. Done!
# Otherwise, increment guess
if ($match) {
if (exists($dict{$guess})) { print "Solution(s): @{$dict{$guess
+}}"; last }
else { print "No words match qualifying guess $guess"; }
}
++$guess;
# Short-circuit: only keep guesses that are sorted
# So when the last char flips to an a, flip the trailing
# string of last chars to a repetition of the rightmost
# non-a
$guess =~ s/([^a])(a+)$/$1 x (length($2)+1)/e;
}
Update! It works, but I feel pretty stupid for all the work of going through all possible guesses when I should just go through the dictionary keys! Gee, it sure is faster that way!
Caution: Contents may have been coded under pressure.
-
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.