Slicing discontinuous data into continuous parts in Ruby
2015-05-24 09:38
399 查看
I have this discontinuous array:
I need it to be an array of continuous arrays:
method 1:
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]]
method 1:
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]]
method 2:
a = [1, 2, 3, 7, 8, 10, 11, 12] prev = a.first p a.slice_before { |e| prev, prev2 = e, prev prev2 + 1 != e }.to_a
method 3:
([a[0]] + a).each_cons(2).slice_before{|k, l| k + 1 != l}.map{|a| a.map(&:last)}
相关文章推荐
- Parse JSON into ordered data-structure (in python)
- Import Access data into Excel in Excel vba
- import CSV data into MySQL via PyMySQL in Python 3.3
- using an enumerable built-in Ruby to access and manipulate nested data
- Dividing fixnum to few parts in ruby
- Insight into DOMDocument - how to convert data from XML to array in PHP
- the way to compart a long code line into parts in order to make the Horizontal scroll bar disappear in V.S' Text Editor
- Sorting Displays in Data View Web Parts (转)
- Whats the best way to split an array in ruby into multiple smaller arrays of random size
- CodeFluent Entities: How to add intellisense into Parts XML development in Visual Studio ?
- FW:Data View Web Parts and Ghosting in SharePoint Version 2
- write data into a txt file in C#
- Convert Geometry data into a Geography data in MS SQL Server
- Alex学Ruby[ method lookup in Ruby 和 include && extend]
- How To Get Properties Data in Spring
- Playback audio data from memory in windows
- CRUD data in LDAP with spring v3.x
- 【跟着stackoverflow学Pandas】add one row in a pandas.DataFrame -DataFrame添加行
- sybase在进行bcp in时报”Unexpected EOF encountered in BCP data-file”
- 【NDN VANET】Data Naming in Vehicle-to-Vehicle Communications 学习笔记