我想根据值的接近度和值之间的给定间隔将值分组到一个数组中。
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
来解决这个问题,但是没有成功。谢谢
最佳答案
我认为这将完成工作,即使可能有更好的解决方案(如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]]
如你所愿。