Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
如何在数组中找到差异最小的两个元素?
换句话说,如何找到具有最小标准偏差的两个元素。
例如,如果我有一个像这样的数组:
arr = [158,2,15,38,17,91]
结果将是 15 和 17。
我假设问题是,“数组的哪两个元素是它们差异最小值的绝对值?”。
arr.combination(2).min_by { |a,b| (a-b).abs } #=> [15, 17]
请参阅Array#combination和Enumerable#min_by。