use v5.12.0; use warnings; #use Data::Dump; use List::Util qw/reduce min pairs sum/; use Test::More; my @tasks1 = pairs map { m/^\s+(?:Input:.*=|Output:) (.*)$/ } split /\n/, <<'=cut'; =pod You are given a list of time points, at least 2, in the 24-hour clock format HH:MM. Write a script to find out the shortest time in minutes between any two time points. Example 1 Input: @time = ("00:00", "23:55", "20:00") Output: 5 Since the difference between "00:00" and "23:55" is the shortest (5 minutes). Example 2 Input: @array = ("01:01", "00:50", "00:57") Output: 4 Example 3 Input: @array = ("10:10", "09:30", "09:00", "09:55") Output: 15 =cut sub solve1 { my @times = @_; my $min = 24*60; # max start my @minutes = sort { $a <=> $b } map { ($a,$b) = split /:/; $a*60+$b } @times; push @minutes, $minutes[0] + $min; # wrap reduce { $min = min( $min, $b-$a); $b } @minutes; return $min; } say "--- Task 1"; is( solve1( eval($_->[0])) => $_->[1] => join " -> ", @$_ ) for @tasks1; my @tasks2 = pairs map { m/^\s+(?:Input:.*=|Output:) (.*)$/ } split /\n/, <<'=cut'; =pod You are given an array of integers having even number of elements.. Write a script to find the maximum sum of the minimum of each pairs. Example 1 Input: @array = (1,2,3,4) Output: 4 Possible Pairings are as below: a) (1,2) and (3,4). So min(1,2) + min(3,4) => 1 + 3 => 4 b) (1,3) and (2,4). So min(1,3) + min(2,4) => 1 + 2 => 3 c) (1,4) and (2,3). So min(1,4) + min(2,3) => 2 + 1 => 3 So the maxium sum is 4. Example 2 Input: @array = (0,2,1,3) Output: 2 Possible Pairings are as below: a) (0,2) and (1,3). So min(0,2) + min(1,3) => 0 + 1 => 1 b) (0,1) and (2,3). So min(0,1) + min(2,3) => 0 + 2 => 2 c) (0,3) and (2,1). So min(0,3) + min(2,1) => 0 + 1 => 1 So the maximum sum is 2. =cut sub solve2 { my @array = @_; return sum map {$_->[0]} pairs sort { $a <=> $b } @array; } say "--- Task 2"; is( solve2( eval($_->[0])) => $_->[1] => join " -> ", @$_ ) for @tasks2; done_testing; #### --- Task 1 ok 1 - ("00:00", "23:55", "20:00") -> 5 ok 2 - ("01:01", "00:50", "00:57") -> 4 ok 3 - ("10:10", "09:30", "09:00", "09:55") -> 15 --- Task 2 ok 4 - (1,2,3,4) -> 4 ok 5 - (0,2,1,3) -> 2 1..5