2017-10-19 117 views
0

有沒有一種優雅的方法來將整數數組分組到Ruby中的範圍數組?紅寶石組整數數組到範圍數組

range1 = [*39..45] 
#=> [39, 40, 41, 42, 43, 44, 45] 

range2 = [*49..52] 
#=> [49, 50, 51, 52] 

range = range1 + range2 
#=> [39, 40, 41, 42, 43, 44, 45, 49, 50, 51, 52] 

range.build_ranges 
#=> [39..45, 49..52] 
+0

另外這裏:https://stackoverflow.com/questions/23840815/grouping-consecutive-numbers-in-an-array – tokland

回答

1

是的。

鑑於原始數組已經排序和uniqued:

[39, 40, 41, 42, 43, 44, 45, 49, 50, 51, 52] 
.chunk_while{|i, j| i.next == j} 
.map{|a| a.first..a.last} 
# => [39..45, 49..52]