I'd like to take input such as:
[1,2,4,5,6,7,9,13]
and turn it into something like the following:
[[1,2],[4,7],[9,9],[13,13]]
Each sub-array represents a range of integers.
I'd like to take input such as:
[1,2,4,5,6,7,9,13]
and turn it into something like the following:
[[1,2],[4,7],[9,9],[13,13]]
Each sub-array represents a range of integers.
An even easier solution than @tokland's very nice one is using
chunk_while
:Note:
chunk_while
was introduced in Ruby 2.3Functional approach using Enumerable#chunk:
How it works: once indexed, consecutive elements in the array have the same
x - idx
, so we use that value to chunk (grouping of consecutive items) the input array. Finally we just need to take the first and last elements of each group to build the pairs.Hmm, well, it's not tokland's masterpiece, but I think it may be a good straightforward solution...
This is almost straight from the enumerable#slice_before method documentation:
This should work with characters, dates, anything with a
.succ
method.Another approach
Similar to Larsenal's method but using inject to manage the boring stuff.