Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing discontinuous data into continuous parts in Ruby

Tags:

arrays

ruby

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.

like image 837
tybro0103 Avatar asked Mar 23 '23 01:03

tybro0103


2 Answers

([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]]
like image 80
sawa Avatar answered Apr 11 '23 03:04

sawa


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]]
like image 29
falsetru Avatar answered Apr 11 '23 03:04

falsetru