Last active
August 29, 2015 14:07
-
-
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.
This file contains 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 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) |
Author
mattantonelli
commented
Sep 30, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment