Skip to content

Instantly share code, notes, and snippets.

@mattantonelli
Last active August 29, 2015 14:07
Show Gist options
  • Save mattantonelli/11e91c249cbfcdc8d57a to your computer and use it in GitHub Desktop.
Save mattantonelli/11e91c249cbfcdc8d57a to your computer and use it in GitHub Desktop.
Take an array of numbers and condense it into a list of ranges using recursion.
def find_range(a, str = '')
return str[2..-1] if a.empty?
start_val = end_val = a[0]
a.each do |val|
break if val > end_val + 1
end_val = val
end
if start_val == end_val
str << ", #{end_val}"
else
str << ", #{start_val}-#{end_val}"
end
find_range(a.drop(a.find_index(end_val) + 1), str)
end
a = [1, 2, 3, 6, 7, 8, 10, 12, 14, 16, 17, 18]
puts find_range(a)
@mattantonelli
Copy link
Author

1-3, 6-8, 10, 12, 14, 16-18

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment