如何查找/过滤具有最小正差的数组元素 [英] how to find/filter the array element with the smallest positive difference

查看:102
本文介绍了如何查找/过滤具有最小正差的数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Swift,我试图对复杂的数组过滤器或排序进行锻炼,但遇到了麻烦.我的整数数组可以包含1到7个元素.给定某个不在数组中的整数值(例如X),我想找到在自身和X之间的差异最小的数组元素.

Using Swift, I am trying to workout a complex array filter or sort and I am stuck. My array of integers can contain between 1 and 7 elements. Given a certain integer value (say X) which is not in the array, I would like to find the array element that gives the smallest difference between itself and X.

推荐答案

Swift 2 中,您可以将其作为具有功能样式的单线"来完成 编程:

In Swift 2 you can do it as a "one-liner" with functional-style programming:

let numbers = [ 1, 3, 7, 11]
let x = 6

let closest = numbers.enumerate().minElement( { abs($0.1 - x) < abs($1.1 - x)} )!

print(closest.element) // 7 = the closest element
print(closest.index)   // 2 = index of the closest element

enumerate()遍历所有数组元素以及 相应的索引,而minElement()返回最小" 关于闭包的(index, element)对. 闭包比较差的绝对值 x的两个元素.

enumerate() iterates over all array elements together with the corresponding index, and minElement() returns the "smallest" (index, element) pair with respect to the closure. The closure compares the absolute values of the difference of two elements to x.

(这里假定数组不为空,所以minElement() 不返回nil.)

(It is assumed here that the array is not empty, so that minElement() does not return nil.)

请注意,这可能不是大型阵列的最快解决方案, 因为(几乎)全部均对绝对差进行两次计算 数组元素.但是对于小型阵列,这应该没关系.

Note that this is probably not the fastest solution for large arrays, because the absolute differences are computed twice for (almost) all array elements. But for small arrays this should not matter.

快捷键3 :

let numbers = [ 1, 3, 7, 11]
let x = 6
let closest = numbers.enumerated().min( by: { abs($0.1 - x) < abs($1.1 - x) } )!
print(closest.element) // 7
print(closest.offset) // 2

在编辑历史记录中可以找到 Swift 1.2 版本.

The Swift 1.2 version can be found in the edit history.

这篇关于如何查找/过滤具有最小正差的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆