Group_by类似的值 - Ruby

时间:2014-01-13 17:03:13

标签: ruby arrays

我想根据值的接近程度和值之间的给定间隔将值组合在一个数组中。

a=[1,2,5,7,20,25,50,53]

例如,间隔为5:

a=[[1,2,5,7],[20,25],[50,53]]

如果我将间隔更改为2:

a=[[1,2],[5,7],[20],[25],[50],[53]]

我试图用group_by解决这个问题,但没有成功。

由于

3 个答案:

答案 0 :(得分:2)

使用Enumerable#slice_before

def group(a, n)
  prev = a.first
  a.slice_before { |x|
    (x - prev > n).tap { prev = x }
  }.to_a
end

a = [1,2,5,7,20,25,50,53]
group(a, 5) # => [[1, 2, 5, 7], [20, 25], [50, 53]]
group(a, 2) # => [[1, 2], [5, 7], [20], [25], [50], [53]]

答案 1 :(得分:1)

我认为这将完成这项工作,即使可能有更好的解决方案(如同Ruby中一样):

def group array, diff
  array.sort! # To remove if you're sure your array will always be sorted
  # array = array.sort # could be a better solution if you don't want your array to be modified in place
  res = []
  subres = []

  array.each do |elt|
    if subres.count == 0 || elt - subres.last <= diff
      subres << elt
    else
      res << subres
      subres = [elt]
    end
  end
  res << subres unless subres.empty?
  res
end

a = [1, 2, 5, 7, 20, 25, 50, 53]

p group a, 5
p group a, 2

将输出

[[1, 2, 5, 7], [20, 25], [50, 53]]
[[1, 2], [5, 7], [20], [25], [50], [53]]

如你所愿。

答案 2 :(得分:0)

def group(array, interval)
  result = [[array[0]]]
  array.inject do |x, y|
    if y - x <= interval
      result.last << y
      else
        result << [y]
    end
    y
  end
  result
end

a=[1,2,5,7,20,25,50,53]

p group(a, 5) # => [[1, 2, 5, 7], [20, 25], [50, 53]]
p group(a, 2) # => [[1, 2], [5, 7], [20], [25], [50], [53]]