diff options
| author | Dave Jacoby <jacoby.david@gmail.com> | 2020-01-07 22:56:41 -0500 |
|---|---|---|
| committer | Dave Jacoby <jacoby.david@gmail.com> | 2020-01-07 22:56:41 -0500 |
| commit | 6f3f9fd164302ca26d009185c6bf68954e8c5a77 (patch) | |
| tree | ea684b495f2ac1f08c8adba3db99bf34f11837f2 | |
| parent | 85da800ba04a2d5c8e3204e548ab3ddae7a773dc (diff) | |
| download | perlweeklychallenge-club-6f3f9fd164302ca26d009185c6bf68954e8c5a77.tar.gz perlweeklychallenge-club-6f3f9fd164302ca26d009185c6bf68954e8c5a77.tar.bz2 perlweeklychallenge-club-6f3f9fd164302ca26d009185c6bf68954e8c5a77.zip | |
ch-1.pl
| -rw-r--r-- | challenge-042/dave-jacoby/perl5/ch-2.pl | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/challenge-042/dave-jacoby/perl5/ch-2.pl b/challenge-042/dave-jacoby/perl5/ch-2.pl new file mode 100644 index 0000000000..2cb2d701ec --- /dev/null +++ b/challenge-042/dave-jacoby/perl5/ch-2.pl @@ -0,0 +1,37 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use feature qw{ say signatures }; +no warnings qw{ experimental::signatures }; + +# generate the string of braces +my $string; +for ( 0 .. 1 + int rand 9 ) { + $string .= int rand 2 ? '(' : ')'; +} + +# test if the string has matched braces +my $t = test_braces($string); +my $response = $t == 0 ? 'OK' : 'NOT OK'; +say qq{$string - $response}; + +exit; + +# The trick is a stack. When you get a "(", +# you push onto the stack, and when get a ")", +# you pop from the stack. We special-case when +# the stack is empty and we get a ")", immediately +# returning -1, and then returning the number of +# values in the array. A balanced array will return +# 0 + +sub test_braces ( $string ) { + my @x; + for my $i ( split //, $string ) { + return -1 if !scalar @x && $i eq ')'; + pop @x if scalar @x && $i eq ')'; + push @x, '' if $i eq '('; + } + return scalar @x; +} |
