加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 将排序数组划分为连续数组的最佳方法?

发布时间:2020-12-17 04:01:41 所属栏目:百科 来源:网络整理
导读:是否有一种简单的方法或方法将数组分区为 Ruby中连续数字的数组? [1,2,3,5,6,8,10] = [[1,3],[5,6],[8],[10]] 我可以为此做一些例程,但想知道是否有一个快速的方法. 山姆 解决方法 一种方法,包括: arr = [1,10] #1 # If subarray is empty or the current
是否有一种简单的方法或方法将数组分区为 Ruby中连续数字的数组?

[1,2,3,5,6,8,10] => [[1,3],[5,6],[8],[10]]

我可以为此做一些例程,但想知道是否有一个快速的方法.

山姆

解决方法

一种方法,包括:

arr = [1,10]

#1

# If subarray is empty or the current value n is not the last value + 1,# add the subarray [n] to the collection; else append the current value
# to the last subarray that was added to the collection. 

arr.each_with_object([]) { |n,a|
  (a.empty? || n != a.last.last+1) ? a << [n] : a[-1] << n }
  #=> [[1,[10]]

#2

# Change the value of 'group' to the current value n if it is the first
# element in arr or it is not equal to the previous element in arr + 1,# then 'chunk' on 'group' and extract the result from the resulting chunked 
# array.

arr.map.with_index do |n,i|
  group = n if i == 0 || n != arr[i-1] + 1
  [n,group]
end.chunk(&:last)
   .map { |_,c| c.map(&:first) } 
  #=> [[1,[10]]

#3

# If n is the last element of arr,append any number other than n+1 to
# a copy of arr and convert to an enumerator.  Step though the enumerator
# arr.size times,adding the current value to a subarray b,and using
# 'peek' to see if the next value of 'arr' equals the current value plus 1.
# If it does,add the subarray b to the collecton a and set b => [].

enum = (arr+[arr.last]).to_enum
a,b = [],[]
arr.size.times do
  curr = enum.next
  b << curr
  (a << b; b = []) unless curr + 1 == enum.peek 
  end
end
a
  #=> [[1,[10]]

#4

# Add elements n of arr sequentially to an array a,each time first inserting
# an arbitrary separator string SEP when n does not equal the previous value
# of arr + 1,map each element of a to a string,join(' '),split on SEP and
# convert each resulting array of strings to an array of integers.

SEP = '+'
match_val = arr.first
arr.each_with_object([]) do |n,a|
  (a << SEP) unless n == match_val 
  a << n
  match_val = n + 1
end.map(&:to_s)
   .join(' ')
   .split(SEP)
   .map { |s| s.split(' ').map(&:to_i) }
  #=> [[1,[10]]

当arr包含负整数时,所有上述方法都有效.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读