I have this discontinuous array:
a = [1, 2, 3, 7, 8, 10, 11, 12]
I need it to be an array of continuous arrays:
[[1, 2, 3], [7, 8], [10, 11, 12]]
I'm looping through the original, comparing each value to the last to build new arrays:
parts = []
last = nil
a.each do |n|
parts.push [] if last.nil? || last+1 != n
parts.last.push n
last = n
end
It feels dirty and un-Ruby-like. I'm interesting in finding a clean, elegant solution.
([a[0]] + a).each_cons(2).slice_before{|k, l| k + 1 != l}.map{|a| a.map(&:last)}
# => [[1, 2, 3], [7, 8], [10, 11, 12]]
Modified version of @hirolau's.
a = [1, 2, 3, 7, 8, 10, 11, 12]
prev = a[0] - 1
a.slice_before { |cur| [prev + 1 != cur, prev = cur][0] }.to_a
# => [[1, 2, 3], [7, 8], [10, 11, 12]]
prev = a[0] - 1
a.slice_before { |cur|
discontinuous = prev + 1 != cur
prev = cur
discontinuous
}.to_a
# => [[1, 2, 3], [7, 8], [10, 11, 12]]
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