secret
Last active

  • Download Gist
hamin_RPCFN_2.rb
Ruby
1 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
require 'time'
def average_time_of_day(arrival_times)
# This sum value will be used to calculate the average.
sum = 0
 
# next_meridian is the next "am" or "pm" value in the arrival_times, naturally it would be empty for the first arrival_time
next_meridian = ""
# next_day is used to keep the total_time_in_secs block aware of
# whether after the first 'PM to AM' transition in the list of times, the following times are
# also the next day or not. This boolean can later be used to generalize this method further to account
# for an array of arrival times covering more than 2 days.
next_day = false
# This block gives us the sum which we can then divide by the length of the list to get the average
arrival_times.each do |x|
x.include?("am") ? (temp_meridian = "am") : (temp_meridian = "pm")
current_day = Time.parse(x).day
if ((temp_meridian == "am") && (next_meridian == "pm") )|| next_day == true
sum += Time.parse("#{current_day+1} "+ x).to_f
next_meridian = temp_meridian
next_day = true
else
sum += Time.parse(x).to_f
next_meridian = temp_meridian
end
end
# Calculate the actual average clock time
average_time_in_secs = sum / arrival_times.length
puts Time.at(average_time_in_secs).strftime("%I:%M%p")
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.