adamcrussell

Balancing Parentheses

Part 2 of the most recent Perl Weekly Challenge was to generate a random string of open and close parentheses and validate which strings were properly balanced. That is, which contained and equal number of open and closed parentheses.


ch-2.pl
ch-2.pl

What I Did

The string of parentheses is generated by picking a random number between 0 and 1 with rand() and then appending an open parens if the number of less than 0.5 and a close parens otherwise.

Validation is done by looping over the string (by way of a split()) and pushing every open parens we see to a new array. When we encounter a close parens we pop from the array and if we do not find an open parens we return fans immediately. Otherwise we continue in this way and if we end up with an empty array we know that all parens have been matched and the string of parens is balanced.

Sample Run

$ perl perl/ch-2.pl
)))) is not balanced

$ perl perl/ch-2.pl
)(() is not balanced

$ perl perl/ch-2.pl
(()) is balanced

Part 1

The first part of he challenge as to print the decimal whole numbers 0 to 50 in octal (base 8).

The perl builtin function sprintf made this very straightforward.

ch-1.pl
ch-1.pl

Sample Run

$ perl perl/ch-1.pl
Decimal 0 = Octal 0
Decimal 1 = Octal 1
Decimal 2 = Octal 2
Decimal 3 = Octal 3
Decimal 4 = Octal 4
Decimal 5 = Octal 5
Decimal 6 = Octal 6
Decimal 7 = Octal 7
Decimal 8 = Octal 10
Decimal 9 = Octal 11
Decimal 10 = Octal 12
.
.
.
Decimal 47 = Octal 57
Decimal 48 = Octal 60
Decimal 49 = Octal 61
Decimal 50 = Octal 62


Comments for this post were locked by the author