Skip to content

Instantly share code, notes, and snippets.

@kevincolyer
Created January 10, 2020 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevincolyer/5609a525cd7ac3902fe252e2c0351300 to your computer and use it in GitHub Desktop.
Save kevincolyer/5609a525cd7ac3902fe252e2c0351300 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl6
use v6;
use Test;
=begin pod
TASK #1
Octal Number System
Write a script to print decimal number 0 to 50 in Octal Number System.
For example:
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
and so on.
=end pod
# Roll my own version because? Why not!
sub dec-to-oct(Int $n is copy) returns Str {
return "0" if $n==0;
my Str $o = "";
while $n>0 {
$o= $n +& 7 ~ $o; # add lower three bits
$n= $n +> 3 ; # shift off lower three bits
}
return $o;
}
say "Decimal $_ = Octal {dec-to-oct($_)} is sprintf conversion {sprintf "%o", $_}" for ^51;
#!/usr/bin/perl6
use v6;
use Test;
=begin pod
TASK #2
Balanced Brackets
Write a script to generate a string with random number of ( and ) brackets. Then make the script validate the string if it has balanced brackets.
For example:
() - OK
(()) - OK
)( - NOT OK
())() - NOT OK
=end pod
sub match-brackets(Str $t) {
# can never match condition
return False if $t.chars < 2;
# loop counting +1 for open -1 for close.
# zero sum is matching
# positive sum is non matching
# negative is always non matching (and quick exit)
my $open=0;
for ^$t.chars -> $i {
$open++ if $t.substr($i,1) eq '(';
$open-- if $t.substr($i,1) eq ')';
return False if $open < 0;
}
return $open == 0 ?? True !! False ;
}
multi MAIN("test") {
is match-brackets("()") ,True ,"test matching";
is match-brackets(")(") ,False,"test never matching";
is match-brackets("()(") ,False,"test odd open not matching";
is match-brackets("())") ,False,"test odd close not matching";
is match-brackets("((())())"),True ,"test nested matching";
is match-brackets("((())))") ,False,"test nested not matching";
is match-brackets("(a(b(c)d)e(f)g)h"),True ,"test nested matching with alternate chars";
done-testing;
}
multi MAIN() {
for ^20 -> $i {
my Str $c;
my $j=1+(^5).roll;
$c~= ('(',')').pick for ^2*$j;
say (match-brackets($c) ?? " Matching: " !! "Not-Matching: ") ~ $c;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment