Robbie Hatley's Perl Solutions To The Weekly Challenge #206
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-26 through 2023-03-04) is weekly challenge #206.
Task 1 is to write a script which returns the shortest time duration between any two times in an array of 24HR time strings. The tricky bit here was realizing that given any two time strings, the time duration between them can have two values, the smaller being 1440 minutes minus the greater, and it's the shorter duration we want in each case, then pick the shortest among all cases:
for (@arrays){
my @array = @{$_};
my @times = map {60*substr($_,0,2)+substr($_,3,2)} @array;
my @diffs; # elapsed times
for ( my $i = 0 ; $i <= $#times - 1 ; ++$i ){
for ( my $j = $i + 1 ; $j <= $#times - 0 ; ++$j ){
my ($t1, $t2) = sort {$a<=>$b} ($times[$i], $times[$j]);
my $te = $t2 - $t1;
if ($te > 720) {$te = 1440 - $te}
push @diffs, $te}}
my $mindiff = 720;
for (@diffs) {if ($_<$mindiff) {$mindiff=$_}}
say '';
say "Times: @array";
say "Shortest time difference = $mindiff minutes";}
Task 2 is "Given an array of integers having even number of elements, find the maximum sum of the minimum of each pair." This one I found much thornier, as the usually-given shortcut solution on web sites is (as far as I know) unproven. The code I wrote is too messy to paste here, but see this link:
That's it for 206; see you on 207!
Comments
Post a Comment