1 #!/usr/bin/perl
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40 use strict;
41 use warnings;
42
43 shortest_time("00:00", "23:55", "20:00");
44 shortest_time("01:01", "00:50", "00:57");
45 shortest_time("10:10", "09:30", "09:00", "09:55");
46
47 sub shortest_time {
48 my @time_points = @_;
49 die "Not enough timepoints!" unless @time_points > 1;
50 foreach my $t (@time_points) {
51 die "Invalid time format for $t!\n" unless $t =~ m/^\d\d:\d\d/;
52 }
53 print "Input: (" . join(", ", @time_points) . ")\n";
54 my $minimum = 1440;
55 foreach my $first (0..$#time_points) {
56 foreach my $second ($first+1..$#time_points) {
57 my ($A, $B) = ($time_points[$first], $time_points[$second]);
58
59
60 my $diff = time_diff($A, $B);
61 $minimum = $diff if $diff < $minimum;
62 $diff = time_diff($B, $A);
63 $minimum = $diff if $diff < $minimum;
64 }
65 }
66 print "Output: $minimum\n";
67 }
68
69 sub time_diff {
70 my ($A, $B) = @_;
71
72 my $minutes_a = to_minutes($A);
73 my $minutes_b = to_minutes($B);
74 if($minutes_b >= $minutes_a) {
75 return $minutes_b - $minutes_a;
76 }
77
78
79
80 return 1440 + $minutes_b - $minutes_a;
81 }
82
83
84 sub to_minutes {
85 my $time = shift;
86 die "Invalid time format for $time!\n" unless $time =~ m/^\d\d:\d\d/;
87 my ($h, $m) = split /:/, $time;
88 $h =~ s/^0//;
89 $m =~ s/^0//;
90 return $h * 60 + $m;
91 }