diff options
| -rw-r--r-- | challenge-218/steve-g-lynn/blog.txt | 1 | ||||
| -rwxr-xr-x | challenge-218/steve-g-lynn/perl/ch-1.pl | 25 | ||||
| -rwxr-xr-x | challenge-218/steve-g-lynn/perl/ch-2.pl | 52 |
3 files changed, 78 insertions, 0 deletions
diff --git a/challenge-218/steve-g-lynn/blog.txt b/challenge-218/steve-g-lynn/blog.txt new file mode 100644 index 0000000000..40e5ecb8b9 --- /dev/null +++ b/challenge-218/steve-g-lynn/blog.txt @@ -0,0 +1 @@ +https://thiujiac.blogspot.com/2023/05/pwc-218.html diff --git a/challenge-218/steve-g-lynn/perl/ch-1.pl b/challenge-218/steve-g-lynn/perl/ch-1.pl new file mode 100755 index 0000000000..0951ddb2ca --- /dev/null +++ b/challenge-218/steve-g-lynn/perl/ch-1.pl @@ -0,0 +1,25 @@ +#!/usr/bin/env -S perl -wl + +use List::Util qw(max); + +local *maximum_product = sub { + + local *myprod=sub { + $_[0]*$_[1]*$_[2]; + }; + + #-- main part of &maximum_product + my @list = sort {$a <=> $b} @_; + + (scalar(@list) < 2) && (die "Need at least 3 elements in input"); + + max( + &myprod( $list[0], $list[1], $list[-1] ), + &myprod( $list[-1], $list[-2], $list[-3] ) + ); +}; + +print &maximum_product( 3, 1, 2); #6 +print &maximum_product( 4, 1, 3, 2); #24 +print &maximum_product( -1, 0, 1, 3, 1); #3 +print &maximum_product( -8, 2, -9, 0, -4, 3); #216 diff --git a/challenge-218/steve-g-lynn/perl/ch-2.pl b/challenge-218/steve-g-lynn/perl/ch-2.pl new file mode 100755 index 0000000000..ef2cbd7162 --- /dev/null +++ b/challenge-218/steve-g-lynn/perl/ch-2.pl @@ -0,0 +1,52 @@ +#!/usr/bin/env -S perl -wl + +#-- algorithm from https://leetcode.com/problems/score-after-flipping-matrix/solutions/2563853/easy-to-understand-basic-python-solution-with-explanation/ + +use PDL; +use PDL::NiceSlice; +use PDL::AutoLoader; + +sub matrix_score { + + local *flip_col = sub { + my ($col)=@_; + $matrix($col) .= !$matrix($col); + }; + + local *flip_row = sub { + my ($row)=@_; + $matrix(,$row) .= !$matrix(,$row); + }; + + local *binary_row = sub { + my ($row)=@_; + oct '0b' . (join( '', $matrix(,$row)->list)); + }; + + #-- main portion of sub + local ($matrix)=@_; #--pdl + #-- I leave out input validation chores + + my ($ncol, $nrow)=($matrix->dims); + + for my $ctr (0 .. $nrow-1) { + #-- check if row starts with 0, if so, flip + ($matrix(0,$ctr)==0) && (&flip_row($ctr)); + } + + for my $ctr (0 .. $ncol-1) { + #-- check if number of 1's in column < 0.5 * nrow + #-- if so, flip column + ( ($matrix($ctr)->sum) < ($nrow/2) ) && ( &flip_col($ctr) ); + } + + #-- add up binary representations of each row + my $retval=0b0; + for my $ctr (0 .. $nrow-1) { + $retval += &binary_row($ctr); + } + sprintf("%d",$retval); +} + +print &matrix_score(pdl '[0,0,1,1; 1,0,1,0; 1,1,0,0]'); #39 +print &matrix_score(pdl '[[0]]'); #1 |
