Skip to content

Instantly share code, notes, and snippets.

@adamcrussell adamcrussell/ch-1.pl
Created Jan 12, 2020

Embed
What would you like to do?
Perl Weekly Challenge 042
use strict;
use warnings;
##
# Write a script to print decimal number 0 to 50 in octal.
##
MAIN:{
for my $x (0..50){
print "Decimal $x = Octal " . sprintf("%o", $x) . "\n";
}
}
use strict;
use warnings;
##
# Write a script to generate a string with a random
# number of ( and ) parentheses. Make the script validate
# the string for balanced parentheses.
##
use boolean;
use constant LENGTH => 4;
use constant OPEN => "(";
use constant CLOSE => ")";
sub build{
my $s;
for (0 .. (LENGTH - 1)){
my $p = rand() < 0.5 ? OPEN : CLOSE;
$s .= $p;
}
return $s;
}
sub validate{
my($s) = @_;
my @a;
for my $c (split(//, $s)){
push @a, $c if($c eq OPEN);
if($c eq CLOSE){
return false if(!@a || pop @a ne OPEN);
}
}
return true if !@a;
return false;
}
MAIN:{
my $s = build();
my $r = validate($s) ? "balanced" : "not balanced";
print "$s is $r\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.