secret
Last active

  • Download Gist
vikasmaskeri.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
def average_time_of_day(time_array)
hours= minutes = count= 0 # initialize
y=[] # initialize
time_array.each do |t|
t1 = t.split(':') # Parse the string to find the time
if (t1.last.end_with?('am') && (t1.first.to_i < 10)) # Count the total no. of am
count +=1
end
hours += t1.first.to_i # total hours
minutes += t1.last.chop.chop.to_i # total minutes
end
hours+= (minutes/60) + (12*count) # recalculating the no. of hours for the time in 'am'
minutes = minutes%60 # recalculating the no. of minutes after updating the no. of hours
total_time = hours*60 + minutes # total time in minutes
average_time = total_time/(time_array.length) # average time in minutes
average_hours = (average_time/60)%12 # average no. of hours
average_minutes = average_time%60 # average no. of minutes
part = average_hours < 10 ? "am" : "pm" # time of the day i.e. am or pm
puts "#{average_hours}:#{average_minutes}#{part}"
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.