ruby - How to find two elements that have smallest difference in an array? -
how find 2 elements in array have smallest difference?
in other words, how find 2 elements have smallest standard deviation.
for instance, if have array like:
arr = [158,2,15,38,17,91]
the result 15 , 17.
i assume question is, "for 2 elements of array absolute value of difference minimum?".
arr.combination(2).min_by { |a,b| (a-b).abs } #=> [15, 17]
Comments
Post a Comment