Re: Perl Quiz of the Week #23
John Douglas Porter <johndporter-/[email protected]>
| Newsgroups | gmane.comp.lang.perl.qotw.discuss |
|---|---|
| Message-ID | <[email protected]> |
Guess I'm a little late, but here are two solutions which
I think are more or less canonical:
# this recursive solution uniqifies at every step.
sub parens_recursive
{
$_[0] == 1 ? ('()') : sort keys %{ { map { ( "()$_" => 1, "($_)" =>
1, "$_()" => 1 ) } parens($_[0]-1) } }
}
# this iterative solution does a Grand Uniqification at the end.
sub parens_iterative
{
my $n = shift;
my @a = ('()');
while ( --$n )
{
@a = map { ( "$_()", "($_)", "()$_" ) } @a;
}
sort keys %{{ map { $_ => 1 } @a }}
}
What I have a hard time understanding is why anyone would approach
this problem as anything other than a string-building task.
Is a math-based approach, for example, more general?
--
John D. Porter
__________________________________
Do you Yahoo!?
Yahoo! Mail - 50x more storage than other providers!
http://promotions.yahoo.com/new_mail