Skip to content

Instantly share code, notes, and snippets.

@armstrjare
Created March 24, 2012 03:39
Show Gist options
  • Save armstrjare/2177940 to your computer and use it in GitHub Desktop.
Save armstrjare/2177940 to your computer and use it in GitHub Desktop.
nums = [1,2,3,5,8,9,12,13,14,15,16,19]
def numbers_grouped(nums)
nums = nums.sort
start, last = nums.first, nil
sequences = []
nums.each_with_index do |num, i|
# Are we out of sequence?
if last && last+1 != num
sequences << [start, last]
start = num
end
# Last iteration, still in sequence
if (i+1) == nums.length
sequences << [start, num]
else
last = num
end
end
sequences
end
puts nums.inspect
puts numbers_grouped(nums).inspect
puts numbers_grouped(nums).map { |s| s.uniq.join('-') }.inspect
==>
[1, 2, 3, 5, 8, 9, 12, 13, 14, 15, 16]
[[1, 3], [5, 5], [8, 9], [12, 16]]
["1-3", "5", "8-9", "12-16"]
@nikz
Copy link

nikz commented Mar 24, 2012

have to use #next not +1 so it also works for letters but yeah.

@Bandit
Copy link

Bandit commented Mar 24, 2012

Nice Jared!

@armstrjare
Copy link
Author

numbers.reduce([]) { |memo, n|
  if memo.last && memo.last.last.next == n
    memo.last.push(n)
  else 
    memo.push([n])
  end
  memo
}.map { |group| [group.first, group.last].uniq.join('-') }

@armstrjare
Copy link
Author

numbers.sort.each_with_object([]) { |n, groups|
  if groups.last && groups.last.last.next == n
    groups.last.push(n)
  else 
    groups.push([n])
  end
}.map { |group| [group.first, group.last].uniq.join('-') }

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