diff options
| author | Bob Lied <boblied+github@gmail.com> | 2024-05-26 22:09:54 -0500 |
|---|---|---|
| committer | Bob Lied <boblied+github@gmail.com> | 2024-05-26 22:09:54 -0500 |
| commit | 393f04b5ef3b2bc43af049a43670654eed014921 (patch) | |
| tree | e39e909117b9ccf1d6ab5c4dd9180e23a1628146 | |
| parent | af5b3b0fffc9112d17193b097a226eeeae90986c (diff) | |
| download | perlweeklychallenge-club-393f04b5ef3b2bc43af049a43670654eed014921.tar.gz perlweeklychallenge-club-393f04b5ef3b2bc43af049a43670654eed014921.tar.bz2 perlweeklychallenge-club-393f04b5ef3b2bc43af049a43670654eed014921.zip | |
Task 1 change to shortcut evaluation above and below
| -rw-r--r-- | challenge-270/bob-lied/perl/ch-1.pl | 31 |
1 files changed, 29 insertions, 2 deletions
diff --git a/challenge-270/bob-lied/perl/ch-1.pl b/challenge-270/bob-lied/perl/ch-1.pl index 5cbd51f959..84d9b14946 100644 --- a/challenge-270/bob-lied/perl/ch-1.pl +++ b/challenge-270/bob-lied/perl/ch-1.pl @@ -33,14 +33,27 @@ my $DoTest = 0; GetOptions("test" => \$DoTest, "verbose" => \$Verbose); exit(!runTest()) if $DoTest; +# Extract a column from a matrix sub columnOf($matrix, $col) { map { $_->[$col] } $matrix->@*; } +# Extract the column above a row, not including the row +sub above($matrix, $row, $col) +{ + map { $_->[$col] } $matrix->@[0 .. $row-1]; +} + +# Extract the column below a row, not including the row +sub below($matrix, $row, $col) +{ + map { $_->[$col] } $matrix->@[$row+1 .. $matrix->$#*]; +} + sub specialPos($matrix) { - use List::Util qw/sum/; + use List::Util qw/sum all/; use List::MoreUtils qw/indexes/; my $special = 0; @@ -48,7 +61,10 @@ sub specialPos($matrix) for ( 0 .. $matrix->$#* ) { my @ones = indexes { $_ == 1 } $matrix->[$_]->@*; - $special++ unless ( @ones != 1 ) || (sum columnOf($matrix, $ones[0]) ) != 1; + + $special++ if ( @ones == 1 ) + && ( all { $_ == 0 } above($matrix, $_, $ones[0]) ) + && ( all { $_ == 0 } below($matrix, $_, $ones[0]) ); } return $special; @@ -59,6 +75,14 @@ sub runTest use Test2::V0; my $matrix = [ [1,0,0], [0,0,1], [1,0,0] ]; + is( [ above($matrix, 0, 0) ], [], "Above 0,0"); + is( [ above($matrix, 1, 0) ], [ 1 ], "Above 1,0"); + is( [ above($matrix, 2, 0) ], [ 1, 0 ], "Above 2,0"); + is( [ below($matrix, 0, 1) ], [ 0, 0 ], "Below 0,0"); + is( [ below($matrix, 1, 1) ], [ 0 ], "Below 1,0"); + is( [ below($matrix, 2, 1) ], [ ], "Below 2,0"); + is( [ below($matrix, 2, 2) ], [ ], "Below 2,2"); + is( specialPos($matrix), 1, "Example 1"); $matrix = [ [1,0,0], [0,1,0], [0,0,1] ]; @@ -73,6 +97,9 @@ sub runTest $matrix = [ [0,0], [1,0], [0,0], [1,1] ]; is( specialPos($matrix), 0, "row > col"); + $matrix = [ [0,0], [1,0], [0,0], [0,0] ]; + is( specialPos($matrix), 1, "row > col, with special"); + $matrix = [ [1] ]; is( specialPos($matrix), 1, "degenerate 1x1 with 1"); |
