[SPOILER] Solution to QOTW 23
Muir Manders <[email protected]>
| Newsgroups | gmane.comp.lang.perl.qotw.discuss |
|---|---|
| Message-ID | <[email protected]> |
This is my first submission to qotw, so tell me if I'm doing something
stupid. This is just a run-of-the-mill recursive solution so it's
nothing new, but all the cool people are sending solutions so I
thought I would too.
#!/usr/bin/perl
print_parens(2 * $ARGV[0], "", 0);
sub print_parens {
my ( $n, $str, $num_open ) = @_;
print "$str\n" if $n == 0;
print_parens( $n - 1, $str . ')', $num_open - 1 ) if $num_open > 0;
print_parens( $n - 1, $str . '(', $num_open + 1 ) if $n-$num_open > 0;
}
and here's a slightly obfuscated version:
sub p{my($x,$q,$p)=@_;!$x?print"$q\n":$p?p($x-1,"$q)",$p-1):0;$x>$p?p($x-1,"$q(",$p+1):0}p
2*shift
Muir Manders