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]  

see array#combination , enumerable#min_by.


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -