我想根据值的接近程度和值之间的给定间隔将值组合在一个数组中。
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
解决这个问题,但没有成功。
由于
答案 0 :(得分:2)
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]]