[NBLUG/talk] I hate perl. :-)
Chris Palmer
chris at eff.org
Mon May 29 17:23:06 PDT 2006
William Tracy writes:
> Anyone who uses Perl for a program more than about fifty lines long
> needs to be slapped.
Ahh, but you can cram so much into those 50 lines! ;)
Here is my version. Apart from a few sanity checks (taint checking,
strict and warnings), an expanded command line syntax, and adherence to
my personal style rules, I also added a cache argument so that
duplicates are not printed.
The obvious performance improvement is to turn the recursion into
iteration. This version is very slow.
#!/usr/bin/perl -T
use strict;
use warnings;
unless (@ARGV) {
print STDERR "Usage: $0 word [...]";
exit;
}
for my $wrd (@ARGV) {
print "Anagrams of $wrd:\n";
my %ngrms;
anagrams('', $wrd, \%ngrms);
print map { $_ . "\n" } sort keys %ngrms;
}
sub anagrams {
my ($so_far, $remaining, $cache) = @_;
if (length($remaining) > 0) {
for (my $i = 0; $i < length($remaining); $i++) {
anagrams($so_far . substr($remaining, $i, 1),
substr($remaining, 0, $i) . substr($remaining, $i + 1),
$cache);
}
} else {
$cache->{$so_far} = defined;
}
}
--
http://www.eff.org/about/staff/#chris_palmer
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://nblug.org/pipermail/talk/attachments/20060529/acc927aa/attachment.pgp
More information about the talk
mailing list