Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Average start time handling midnight

by hippo (Bishop)
on Jul 21, 2016 at 12:34 UTC ( [id://1168226]=note: print w/replies, xml ) Need Help??


in reply to Average start time handling midnight

Subtract 24h from all times which are >12:00. Then calculate the mean, which is an offset from midnight. If the mean is < 0, add 24h back onto it.

  • Comment on Re: Average start time handling midnight

Replies are listed 'Best First'.
Re^2: Average start time handling midnight
by GotToBTru (Prior) on Jul 21, 2016 at 12:46 UTC

    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)

      I had rather taken that first example to be an illustration of what chrisjej didn't want. Perhaps we need a better-defined spec?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1168226]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2024-04-24 06:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found