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.
A range of array variables can be indicated by separating the first array index value from the last index value by two decimal points.
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};
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With