I’ve been doing the Perl Weekly
Challenges. The
latest
was about printing in octal and detecting balanced brackets.
Printing the numbers from 0 to 50 in octal is, well, trivial,
because we have printf.
foreach (0..50) {
printf('Decimal %d = Octal %o'."\n",$_,$_);
}
Balancing the brackets is more fun. Generating a random string of
brackets is easy enough (I make sure the number of characters is even,
because if not it won't be balanced anyway).
my $s='';
foreach (-1..2*(int(rand()*4))) {
$s .= (rand()<0.5)?'(':')';
}
Then I repeatedly delete all matched sets of ()
until there are none left.
while ($s =~ s/\(\)//g) {
}
Thus (()))())()
becomes ()))
becomes ))
.
If there are any characters left, the string was unbalanced.
Comments on this post are now closed. If you have particular grounds for adding a late comment, comment on a more recent post quoting the URL of this one.