[SPOILER] Perl Quiz of the Week #23
Ronald J Kimball <[email protected]>
| Newsgroups | gmane.comp.lang.perl.qotw.discuss |
|---|---|
| Message-ID | <[email protected]> |
My initial solution looked a lot like Jose's, but I realized it wasn't
producing all the strings. To get produce strings of length N+1, it's not
enough to add () at the beginning, at the end, and around strings of length
N. Instead, () needs to be added at every spot within the string. So,
here's my solution. It builds up all the strings together, rather than
generating one at a time, so it uses a lot of memory and probably isn't
very fast either. But it was easy to write. :)
#!/usr/local/bin/perl -w
use strict;
my($pairs) = shift or die "Must specify number of pairs.\n";
my %str = ('' => 1);
foreach (1 .. $pairs) {
foreach my $str (keys %str) {
foreach (0 .. length $str) {
my $tmp = $str;
substr($tmp, $_, 0) = "()";
$str{$tmp} = 1;
}
delete $str{$str};
}
}
print "$_\n" for sort keys %str;
__END__
Ronald