Skip to content

Instantly share code, notes, and snippets.

@ipepe
Created Oct 9, 2020
Embed
What would you like to do?
When You need to calculate integer ranges
def ranges(array_of_hours)
ranges = array_of_hours.map do |hour|
(hour..hour)
end
ranges = ranges.sort_by {|r| r.first }
*outages = ranges.shift
ranges.each do |r|
lastr = outages[-1]
if lastr.last >= r.first - 1
outages[-1] = lastr.first..[r.last, lastr.last].max
else
outages.push(r)
end
end
outages
end
result = ranges([1, 2, 3, 4, 6, 8, 9]).join(',')
if result == '1-4,6,8-9'
puts "Congratulations"
else
puts result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment