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; }
But God demonstrates His own love toward us, in that while we were yet sinners, Christ died for us. Romans 5:8 (NASB)


In reply to Re^2: Average start time handling midnight by GotToBTru
in thread Average start time handling midnight by chrisjej

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.