Created
October 9, 2020 11:28
-
-
Save ipepe/c89f067a19730a6f31009f43f24bf7a5 to your computer and use it in GitHub Desktop.
When You need to calculate integer ranges
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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