Question

I have these ranges:

X = [10..17,21..34,40..117,384..399,407..455,989..1013]

What I need is: if the first number of the second range minus the last number of the first range is less than 10, then group them together, else include the range. What I need is the following:

result = [[10..17,21..34,40..117],[384..399,407..455],[989..1013]]

what I've done is this but this does not group more than two together.

Y = []
X.each_cons(2) do |r1,r2|
  if (r2.first - r1.last) < 10
      Y << ((r1.last - r1.first) + (r2.last - r2.first)
  else
      Y << (r1.last - r1.first)
  end
end

# Y = [[10..17,21..34,40..117],[384..399,407..455],[989..1013]]

I like to also then add up all ranges within each element:

Y = [97, 63, 24]

Any help will be appreciated. Thanks in advance.

Était-ce utile?

La solution

prev = X.first.last
# => 17
X.slice_before{|r| (r.first - prev >= 10).tap{prev = r.last}}.to_a
# => [[10..17, 21..34, 40..117], [384..399, 407..455], [989..1013]]
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top