如何找到数组中差异最小的两个元素?
How to find two elements that have smallest difference in an array?
如何找到数组中两个元素的差异最小?
换句话说,如何找到标准偏差最小的两个元素。
例如,如果我有一个像这样的数组:
arr = [158,2,15,38,17,91]
结果将是 15 和 17。
我假设问题是,"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]
如何找到数组中两个元素的差异最小?
换句话说,如何找到标准偏差最小的两个元素。
例如,如果我有一个像这样的数组:
arr = [158,2,15,38,17,91]
结果将是 15 和 17。
我假设问题是,"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]