http://www.perlmonks.org?node_id=517492


in reply to Word Unscrambler

Heh, I wrote something like this for the Neopets word scrambler game, just for the heck of it. I'm on a quest to see how many Neopets games I can achieve Grand Master on using Perl scripts. The interesting thing is that you have to produce all words that can be made from the letters, so it's not as simple as just sorting the letters in order and finding a match. Instead, I make sure that the letter counts for the dictionary word are equal to or smaller than the letter counts for the letter set (plus blanks), then sort the result set by size and alphabetically. I get my results quite fast (a fraction of a second usually), and they'd probably be faster if I went to the bother of eliminating the words larger than 6 letters from the dictionary, since the Neopets game always gives you 6. Also, my algorithm is set up to support blanks, which isn't necessary either unless you want to use this for Scrabble.
use strict; use warnings; my $letters = 'jboiac'; my ($lcount, $blanks, %lhash, $handle, @matches); $lcount = length($letters); $blanks = $letters =~ s/([^a-z])//g; $lhash{$_}++ for split //, $letters; open ($handle, 'dict1.dat'); while (<$handle>) { chomp; push @matches, $_ if scrabble($_); } close ($handle); print join "\n", sort { length($b) <=> length($a) || $a cmp $b } @matc +hes; sub scrabble { return 0 if length($_[0]) > $lcount; my ($nf, %wlhash); $wlhash{$_}++ for split //, $_[0]; for (keys %wlhash) { no warnings; return 0 if $lhash{$_} < $wlhash{$_} && ($nf += $wlhash{$_} - $lhash{$_}) > $blanks; } return 1; }
Returns:
jacobi ciao abc bio boa cab cob jab jib job
(abc wouldn't be allowed in Scrabble, but the Neopets game has some odd words in it, including names of Neopets. I had to add these manually as I went along using a second script)