-1

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.

trincot
  • 317,000
  • 35
  • 244
  • 286
masfmqowkf
  • 121
  • 12
  • 4
    [*Standard deviation*](https://en.wikipedia.org/wiki/Standard_deviation) is an indication of the difference with the mean, not the difference between two values in the data set. – trincot Jul 15 '16 at 18:12
  • Please read "[ask]" including the linked pages, and "[mcve]". We'd like to see your effort, either as the places you searched and why they didn't help, or the code you wrote toward solving the problem. Without the code it looks like you're asking us to write the code for you, which isn't what SO is for. Please read http://meta.stackoverflow.com/q/261592/128421 also as it helps explain the effort side of things. – the Tin Man Jul 15 '16 at 18:59

1 Answers1

8

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.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100