Re: [SPOILER] Solution for QOTW 23
Mark Jason Dominus <[email protected]>
| Newsgroups | gmane.comp.lang.perl.qotw.discuss |
|---|---|
| Message-ID | <[email protected]> |
> print $_ = "()" x shift;
> print while s{^ ( \(+ ) ( \)+ ) \( }
> {"()" x (length($2) - 1)
> . "(" x (length($1) - length($2) + 2)
> . ")"
> }xe;
A couple of people have referred to this as golfing. But it really
isn't golfing; I don't think much of the idea of golf. I wrote the
program this way because I thought it was the clearest way I could
think of to express the algorithm I came up with. If the code is
opaque, I think it's because the algorithm is subtle, not because it's
been obfuscated.
Here's a synthetic version that uses an array instead of a string; I
don't think it's easier to understand. just the opposite, in fact:
#!/usr/bin/perl -l
@a = ('(', ')') x shift;
while (1) {
print @a;
my ($open, $close) = (0, 0);
$open++ while $a[$open] eq "(";
$close++ while $a[$open+$close] eq ")";
last if @a == $open+$close;
for (0 .. $close - 2) {
$a[$_*2+0] = '(';
$a[$_*2+1] = ')';
}
for (0 .. $open - $close + 1) {
$a[$_ + 2*($close - 1)] = '(';
}
$a[$open+$close] = ')';
}