Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I summarize array of integers as an array of ranges?

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.

like image 237
Larsenal Avatar asked Dec 24 '11 00:12

Larsenal


People also ask

How do you specify a range in an array?

A range of array variables can be indicated by separating the first array index value from the last index value by two decimal points.

How do you declare an array of integers?

We declare an array in Java as we do other variables, by providing a type and name: int[] myArray; To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15};

How do you find the range of an array in C++?

Mean of range in array in C++ In the direct approach, for each query, we will loop from the start index to the end index of the range. And add all integers of the array and divide by count. This approach works fine and prints the result but is not an effective one.


2 Answers

Functional approach using Enumerable#chunk:

ranges = [1, 2, 4, 5, 6, 7, 9, 13]
  .enum_for(:chunk) # .chunk for Ruby >= 2.4
  .with_index { |x, idx| x - idx }
  .map { |_diff, group| [group.first, group.last] }

#=> [[1, 2], [4, 7], [9, 9], [13, 13]]

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.

like image 62
tokland Avatar answered Sep 19 '22 09:09

tokland


This is almost straight from the enumerable#slice_before method documentation:

ar = [1,2,4,5,6,7,9,13]
prev = ar[0]
ar.slice_before{|e|prev,prev2 = e,prev; prev2.succ != e}.map{|a|a.first..a.last}
#=> [1..2, 4..7, 9..9, 13..13]

This should work with characters, dates, anything with a .succ method.

like image 25
steenslag Avatar answered Sep 19 '22 09:09

steenslag