Search code examples
rubydifferencedeviation

How to find two elements that have smallest difference in an array?


How do I find two elements in an array that have the smallest difference?

In other words, how to find two elements that have a the smallest standard deviation.

For instance, if I have an array like:

arr = [158,2,15,38,17,91]

the result would be 15 and 17.


Solution

  • I assume the question is, "for which two elements of the array is the absolute value of their difference minimum?".

    arr.combination(2).min_by { |a,b| (a-b).abs }
      #=> [15, 17] 
    

    See Array#combination and Enumerable#min_by.