Task1
We calculate the distance by keeping track of the last letter written:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(min);
sub minimum_time{
my ($str) = @_;
my ($res,$prev) = (0,0);
foreach my $c(split '',$str){
my $curr = ord($c) - ord('a');
my $t = abs($prev - $curr);
$t = min($t,26-$t);
$res += $t+1;
$prev = $curr
}
$res
}
printf "%d\n",minimum_time('abc');
printf "%d\n",minimum_time('bza');
printf "%d\n",minimum_time('zjpc');
Task2
We check if a box contains balls of all the three given colors:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(all);
sub balls_and_boxes{
my ($sum,%h) = (0);
$h{$2} .= $1 while($_[0] =~ /([RGB])(\d)/g);
foreach my $v(values %h){
$sum++ if all{index($v,$_) != -1} ('R','G','B')
}
$sum
}
printf "%d\n",balls_and_boxes('G0B1R2R0B0');
printf "%d\n",balls_and_boxes('G1R3R6B3G6B1B6R1G3');
printf "%d\n",balls_and_boxes('B3B2G1B3');