Created
March 24, 2012 03:39
-
-
Save armstrjare/2177940 to your computer and use it in GitHub Desktop.
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
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"] |
Nice Jared!
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('-') }
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
have to use #next not +1 so it also works for letters but yeah.