RabbitFarm
2021-02-21
The Weekly Challenge 100
The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
Part 1
You are given a time (12 hour / 24 hour). Write a script to convert the given time from 12 hour format to 24 hour format and vice versa.
Solution
perl -e 'shift=~/(\d+):(\d\d\s*((am|pm)))/;if($1 < 12 && $3 eq "pm"){$h = $1 + 12}elsif($1 > 12 && $3 eq "pm"){$h = "0" . ($1 - 12)}else{$h = $1}print "$h:$2\n"' "17:15 pm"
Sample Run
perl -e 'shift=~/(\d+):(\d\d\s*((am|pm)))/;if($1 < 12 && $3 eq "pm"){$h = $1 + 12}elsif($1 > 12 && $3 eq "pm"){$h = "0" . ($1 - 12)}else{$h = $1}print "$h:$2\n"' "17:15 pm"
05:15 pm
perl -e 'shift=~/(\d+):(\d\d\s*((am|pm)))/;if($1 < 12 && $3 eq "pm"){$h = $1 + 12}elsif($1 > 12 && $3 eq "pm"){$h = "0" . ($1 - 12)}else{$h = $1}print "$h:$2\n"' "05:15 pm"
17:15 pm
Notes
Ok, so this isn;t going to win and Perl Golf competitions, that’s for sure! Frankly, this approach using regexes might not be the best for succinctly handling the bi-directionality.
For anyone that might not be familiar shift=~/(\d+):(\d\d\s*((am|pm)))/
means shift the first argument off of @ARGV (the command line arguments and then match against the regex. This is equivalent to $ARGV[0]=~/(\d+):(\d\d\s*((am|pm)))/
.
Part 2
You are given triangle array. Write a script to find the minimum path sum from top to bottom. When you are on index i on the current row then you may move to either index i or index i + 1 on the next row.
Solution
use strict;
use warnings;
sub minimum_sum{
my(@triangle) = @_;
my($i, $j) = (0, 0);
my $sum = $triangle[0]->[0];
while($i < @triangle){
unless(!exists($triangle[$i+1])){
$j = ($triangle[$i+1]->[$j] >= $triangle[$i+1]->[$j+1]) ? $j+1 : $j;
$sum += $triangle[$i+1]->[$j];
}
$i++;
}
return $sum;
}
MAIN:{
my(@TRIANGLE);
@TRIANGLE = ([1], [2, 4], [6, 4, 9], [5, 1 , 7, 2]);
print minimum_sum(@TRIANGLE) . "\n";
@TRIANGLE =([3], [3, 1], [5, 2, 3], [4, 3, 1, 3]);
print minimum_sum(@TRIANGLE) . "\n";
}
Sample Run
$ perl ch-2.pl
8
7
Notes
I think this is a relatively well known greedy tactic. In order to minimize the total sum, make the minimum choice at each step.
References
posted at: 17:09 by: Adam Russell | path: /perl | permanent link to this entry