Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping an array by comparing 2 adjacent elements

Tags:

arrays

ruby

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. For instance:

Original array:

array = [a, b, c, d, e]

and

a.attribute = 1
b.attribute = 3
c.attribute = 6
d.attribute = 9
e.attribute = 10 

If I want to group the elements such that the difference between the attributes of 2 adjacent elements are less or equal than 2, the result should look like so:

END RESULT

result_array = [[a, b], [c], [d, e]]

WHAT I HAVE

def group_elements_by_difference(array, difference)
    result_array = []
    subgroup = []
    last_element_attribute = array.first.attribute
    array.each do |element|
      if element.attribute <= (last_element_attribute + difference)
        subgroup << element
      else
        #add the subgroup to the result_array
        result_array << subgroup
        subgroup = []
        subgroup << element
      end
      #update last_element_attribute
      last_element_attribute = element.attribute
    end
    result_array << subgroup
end

QUESTION

Is there a built in function in Ruby 1.9.3, such as group_by that could replace my group_elements_by_difference?

like image 257
AbM Avatar asked Sep 14 '26 00:09

AbM


1 Answers

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.

like image 163
sawa Avatar answered Sep 16 '26 16:09

sawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!