Skip to content

Instantly share code, notes, and snippets.

@ipepe
Created October 9, 2020 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ipepe/c89f067a19730a6f31009f43f24bf7a5 to your computer and use it in GitHub Desktop.
Save ipepe/c89f067a19730a6f31009f43f24bf7a5 to your computer and use it in GitHub Desktop.
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