Grouping an array by comparing 2 adjacent elements

后端 未结 3 1540
难免孤独
难免孤独 2021-01-21 05:10

I have an array of objects and I would like to group them based on the difference between the attributes of 2 adjacent elements. The array is already sorted by that attribute. F

3条回答
  •  情书的邮戳
    2021-01-21 06:01

    The following uses numerals directly, but the algorithm should be the same as when you do it with attributes. It assumes that all numerals are greater than 0. If not, then replace it with something that works.

    array = [1, 3, 6, 9, 10]
    
    [0, *array].each_cons(2).slice_before{|k, l| l - k > 2}.map{|a| a.map(&:last)}
    # => [[1, 3], [6], [9, 10]]
    

    With attributes, do l.attribute, etc., and replace 0 with a dummy element whose attribute is 0.

提交回复
热议问题