Task1
We count the strings which are prefixes of the given string:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;
sub count_prefixes{
scalar grep {index($_[1], $_) == 0} @{$_[0]}
}
is count_prefixes(['a','ap','app','apple','banana'],'apple'),
4,'Example 1';
is count_prefixes(['cat','dog','fish'],'bird'),0,'Example 2';
is count_prefixes(['hello','he','hell','heaven','he'],'hello'),
4,'Example 3';
is count_prefixes(['','code','coding','cod'],'coding'),
3,'Example 4';
is count_prefixes(['p','pr','pro','prog','progr','progra','program'],
'program'),7,'Example 5';
Task2
We check for valid times by enumerating different possibilities of hours and minutes:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;
sub valid_times{
my $res = 1;
my @t = split '',$_[0];
if($t[0] eq '?') {
$res = $t[1] eq '?' ? 24 : $t[1] lt '4' ? 3 : 2
} elsif($t[1] eq '?') {
$res = $t[0] lt '2' ? 10 : 4
}
$res * ($t[3] eq '?' ? 6 : 1) * ($t[4] eq '?' ? 10 : 1)
}
is valid_times('?2:34'),3,'Example 1';
is valid_times('?4:?0'),12,'Example 2';
is valid_times('??:??'),1440,'Example 3';
is valid_times('?3:45'),3,'Example 4';
is valid_times('2?:15'),4,'Example 5';
No comments:
Post a Comment