Robbie Hatley's Perl Solutions To The Weekly Challenge #204
For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle, usually with two parts, cycling every Sunday. You can find it here:
This week (2023-02-12 through 2023-02-18) is weekly challenge #204.
Task 1 is "determine if an array is monotonic". This is just a matter of using the "&&=", "<=", and ">=" operators:
sub is_mono (@a){
my $mono;
$mono = 1;
for ( my $i = 1 ; $i <= $#a ; ++$i ){
$mono &&= ($a[$i-1]<=$a[$i]);} # mono inc?
if ( $mono == 1 ) {return 1;}
$mono = 1;
for ( my $i = 1 ; $i <= $#a ; ++$i ){
$mono &&= ($a[$i-1]>=$a[$i]);} # mono dec?
if ( $mono == 1 ) {return 2;}
return 0;}
Task 2 is "reshape array". The approach I took was to first note the original shape, then record the elements in a flat array, then note the desired shape, then reshape if possible:
sub shape {
my $r = shift @_;
my $c = shift @_;
my @flat = @_;
if ($r*$c != scalar @flat){
return ([0])}
my @rows;
my $i = 0;
for (@flat){
$rows[int $i/$c]->[$i%$c]=$_;
++$i}
return @rows}
That's it for 204; looking forward to 205.
Comments
Post a Comment