Your algorithm has trouble with the first example, 11a and 1pm. Average of 11 and -11 is 0.
Update (and updated again - no need to test for negative average (and updated again to allow minutes along with hours)):
use strict; use warnings; use Test::Simple tests => 8; ok(&avg('01:05','03:13') eq '02:09', 'AM Only'); ok(&avg('20:43','22:45') eq '21:44', 'PM Only'); ok(&avg('09:00','13:00') eq '11:00', 'AM to PM'); ok(&avg('15:12','01:52') eq '20:32', 'PM to AM next day'); ok(&avg('09:10','07:08') eq '20:09', 'AM to AM next day'); ok(&avg('15:02','13:30') eq '02:16', 'PM to PM next day'); ok(&avg('11:00','13:00') eq '12:00', 'OP Example 1'); ok(&avg('23:00','01:00') eq '00:00', 'OP Example 2'); sub avg { my ($x,$y) = @_; $x = ttoi($x); $y = ttoi($y); if ($y < $x) { $y += (24 * 60); } return itot((($x + $y)/2) % (24 * 60)); } sub ttoi { my $t = shift; my ($h,$m) = split /:/,$t; return $h * 60 + $m; } sub itot { my $i=shift; my $h = $i / 60; my $m = $i % 60; return sprintf "%02d:%02d",$h,$m; }
In reply to Re^2: Average start time handling midnight
by GotToBTru
in thread Average start time handling midnight
by chrisjej
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |