"What word in the English language has 15 letters, none of which is
repeated?"
This was the question on the blackboard in a local branch of a
well-known purveyor of over-priced, burnt coffee, and if you knew the
answer you could get a free latte. I though to myself "Perl could help
find the answer to that", and I set about writing the following code:
#!/usr/bin/perl -w
use strict;
use diagnostics;
# open DICT, "/usr/dict/words";
open DICT, "/tmp/web2.txt";
my @words_of_15_letters;
while (<DICT>) {
push @words_of_15_letters, $_ if /^.{15}$/;
}
print "Number of words found ", scalar @words_of_15_letters, "\n";
foreach my $word (@words_of_15_letters) {
my %letter_count;
my $repeat_found;
foreach my $letter (split //, $word) {
$letter_count{$letter}++;
}
foreach (keys %letter_count) {
$repeat_found = 1 if $letter_count{$_} > 1;
}
print $word unless $repeat_found;
}
The first thing I found was that
/usr/dict/words doesn't
have the answer. It has too few words in it. I downloaded a dictionary
file from
puzzlers.org that had about 5 times more words in it.
This code finds the right answer, but I would like to know if anyone
can improve it. It seems much more
long-winded than it needs to
be. Is there any way of making it more succinct? In particular, is
there a way to check for repeated letters in the pattern match?
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.