Created
March 24, 2012 07:37
-
-
Save armstrjare/2179652 to your computer and use it in GitHub Desktop.
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
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 | |
def group_sequential1(nums) | |
nums.sort.inject([]) { |memo, num| | |
if memo.last && memo.last.last.next == num | |
memo.last << num | |
else | |
memo << [num] | |
end | |
memo | |
} | |
end | |
def group_sequential2(nums) | |
prev = nil | |
# Enum#slice_before is ruby 1.9 | |
nums.sort.slice_before { |num| | |
sequential = !prev || prev.next == num | |
prev = num | |
!sequential # Don't slice on sequential | |
}.to_a | |
end | |
puts nums.inspect | |
puts numbers_grouped(nums).inspect | |
puts numbers_grouped(nums).map { |s| s.uniq.join('-') }.inspect | |
puts group_sequential1(nums).inspect | |
puts group_sequential1(nums).map { |a| [a.first, a.last].uniq.join('-') }.inspect | |
puts group_sequential2(nums).inspect | |
puts group_sequential2(nums).map { |a| [a.first, a.last].uniq.join('-') }.inspect | |
===> | |
[1, 2, 3, 5, 8, 9, 12, 13, 14, 15, 16, 19] | |
[[1, 3], [5, 5], [8, 9], [12, 16], [19, 19]] | |
["1-3", "5", "8-9", "12-16", "19"] | |
[[1, 2, 3], [5], [8, 9], [12, 13, 14, 15, 16], [19]] | |
["1-3", "5", "8-9", "12-16", "19"] | |
[[1, 2, 3], [5], [8, 9], [12, 13, 14, 15, 16], [19]] | |
["1-3", "5", "8-9", "12-16", "19"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment