Welcome to the Monastery | |
PerlMonks |
Re: N Permutations of M Itemsby Zaxo (Archbishop) |
on Dec 20, 2002 at 08:27 UTC ( [id://221385]=note: print w/replies, xml ) | Need Help?? |
It's better to avoid checking all permutations if you can. Permutations grow in number very rapidly with string length. You don't need to know which permutation gets you a dictionary word, only that one exists. You can do that by rearranging the characters of words in alphabetical order and matching with wildcards. We deal with 'location' in the form 'acilnoot'. First, let's get the preliminaries out of the way... and make an anagram dictionary. That's not necessary, but it will speed things up if the wordlist is not too long for memory.
It would be nice to give several words on the command line, so we set that up in a hash which will hold results:
Now, for instance, 'coal' appears in the %words dictionary under the key 'aclo'. We can construct the regex /a.*c.*l.*o/. If 'acilnoot' matches, then 'location' contains 'coal'. I've fancied up the regex to capture unused characters (just in case that may be handy ;-), though there is no use made of that here. I also arranged for length check to save time on hopeless cases. Finally, print results just to have something to show for all that.
Running this on my machine as 'time perl anaword.pl location brevity Zoroaster' prints: I didn't show how to limit attention to four letter words, but that is easy given the structure of this treatment. There are other nodes here which use this technique. Search 'anagram' to find them. Update: Modified regex to anchor at the ends and not miss unused characters, updated times to the new values. After Compline,
In Section
Seekers of Perl Wisdom
|
|