#!/usr/bin/ruby

#
## http://rosettacode.org/wiki/Averages/Mean_time_of_day
#

func mean_angle(angles) {
    atan2(
        Math.avg(angles.map { .deg2rad.sin }...),
        Math.avg(angles.map { .deg2rad.cos }...),
    ).rad2deg;
}

func time2deg(t) {
  (var m = t.match(/^(\d\d):(\d\d):(\d\d)$/)) || die "invalid time";
  var (hh,mm,ss) = m.cap.map{.to_i}...;
  ((hh ~~ range(24)) && (mm ~~ range(60)) && (ss ~~ range(60))) || die "invalid time";
  (hh*3600 + mm*60 + ss) * 360 / 86400;
}
 
func deg2time(d) {
  var sec = ((d % 360) * 86400 / 360);
  "%02d:%02d:%02d" % (sec/3600, (sec%3600)/60, sec%60);
}
 
func mean_time(times) {
  deg2time(mean_angle(times.map {|t| time2deg(t)}));
}
 
say mean_time(["23:00:17", "23:40:20", "00:12:45", "00:17:19"]);
