Balanced brackets: Difference between revisions

From Rosetta Code
Content added Content deleted
(created page - Perl 6 code)
 
(→‎{{header|Perl 6}}: slight improvement)
Line 26: Line 26:


my $N = get;
my $N = get;
my $s = ("[" xx $N, "]" xx $N).pick(*).join;
my $s = (<[ ]> xx $N).pick(*).join;
say "$s {balanced($s) ?? "is" !! "is not"} well-balanced"</lang>
say "$s {balanced($s) ?? "is" !! "is not"} well-balanced"</lang>

Revision as of 10:25, 20 February 2011

Task
Balanced brackets
You are encouraged to solve this task according to the task description, using any language you may know.

Problem: Generate a string with $N opening brackets ("[") and $N closing brackets ("]"), in some arbitrary order. Determine whether the string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.

Examples:

   (empty)   OK
   []        OK   ][        NOT OK
   [][]      OK   ][][      NOT OK
   [[][]]    OK   []][[]    NOT OK

Perl 6

<lang perl6>sub balanced($s) {

   my $l = 0;
   for $s.comb {
       when "]" {
           --$l;
           return False if $l < 0;
       }
       when "[" {
           ++$l;
       }
   }
   return $l == 0;

}

my $N = get; my $s = (<[ ]> xx $N).pick(*).join; say "$s {balanced($s) ?? "is" !! "is not"} well-balanced"</lang>