当我引用数组中的某个项目时,我想找到最接近它且符合特定条件(向前或向后)的另一个项目。
例如,我有这个数组:
let items = [
(a: "Item 1", b: "F", c: 3),
(a: "Item 2", b: "S", c: 5),
(a: "Item 3", b: "D", c: 7),
(a: "Item 4", b: "A", c: 9),
(a: "Item 5", b: "M", c: 11),
(a: "Item 6", b: "I", c: 13),
(a: "Item 7", b: "F", c: 15),
(a: "Item 8", b: "S", c: 17),
(a: "Item 9", b: "D", c: 19),
(a: "Item 10", b: "A", c: 21),
(a: "Item 11", b: "M", c: 23),
(a: "Item 12", b: "I", c: 13),
(a: "Item 13", b: "F", c: 15),
(a: "Item 14", b: "S", c: 17),
(a: "Item 15", b: "D", c: 19),
(a: "Item 16", b: "A", c: 21),
(a: "Item 17", b: "M", c: 23),
(a: "Item 18", b: "I", c: 13),
(a: "Item 19", b: "F", c: 15),
(a: "Item 20", b: "S", c: 17),
(a: "Item 21", b: "D", c: 19),
(a: "Item 22", b: "A", c: 21),
(a: "Item 23", b: "M", c: 23),
(a: "Item 24", b: "I", c: 13)
]
现在假设我有
item[7]
,我怎样才能找到最接近的有 b = "I"
的项目?我只能想到一些嵌套的 for 循环,但听起来很混乱,而且性能不佳。另请记住,我不希望在搜索时出现 out of range
问题。关于如何处理这个问题有类似 Swift 的想法吗?
以下是 Array 上的泛型,它应该可以满足您的需求。它返回一个包含最接近匹配的索引和值的元组:
extension Array {
func closestMatch(_ index:Index, predicate:(Element)->Bool) -> (Int, Element)? {
if predicate(self[index]) {
return (index, self[index])
}
var delta = 1
while(true) {
guard index + delta < count || index - delta >= 0 else {
return nil
}
if index + delta < count && predicate(self[index + delta]) {
return (index + delta, self[index + delta])
}
if index - delta >= 0 && predicate(self[index - delta]) {
return (index - delta, self[index - delta])
}
delta = delta + 1
}
}
}
print(items.closestMatch(7) { $0.1 == "I" })
使用高阶函数的优化解决方案:
func closestMatch(values: [Int64], inputValue: Int64) -> Int64? {
return (values.reduce(values[0]) { abs($0-inputValue) < abs($1-inputValue) ? $0 : $1 })
}
Swift 每个版本都在不断进步,以优化性能和效率。通过此实现,使用高阶函数在值数组中查找最接近的匹配要容易得多。根据您的需要更改值的类型。
假代码:
int index = 7;
int delta = 0;
while (true)
{
delta = delta + 1;
if ( index - delta >= 0 && matches(items[ index - delta]) {
// Found closest index on Left : index-delta
break;
}
if ( index + delta < items.length && matches(items[ index + delta]) {
// Found closest index on Right: index + delta
break;
}
}
// Time complexity: O(N)
您可以轻松地将假代码转换为 Swift 代码。
除了其他解决方案之外,“一行”:
let index = 7
let searchString = "I"
let result = items.enumerate()
.filter { $0.1.b == searchString }
.map { (abs(index - $0.0), $0.1) }
.minElement { $0.0 < $1.0 }
.map { $0.1 }
print(result) // Optional(("Item 6", "I", 13))
基于 David Berry 的回答:
extension Array {
func closestMatch(index: Index, predicate: (Element) -> Bool) -> Element? {
return enumerate().filter { predicate($0.1) }.map { (abs(index - $0.0), $0.1) }.minElement { $0.0 < $1.0 }.map { $0.1 }
}
}
print(items.closestMatch(7) { $0.1 == "I" }) // Optional(("Item 6", "I", 13))
注意: 就性能而言,David Berry 的答案更好。
此功能应该有效:
func findClosestItem(index: Int, items: [(a: String, b: String, c: Int)]) -> (a: String, b: String, c: Int)? {
guard index < items.count && index > -1 else{
return nil
}
var foundItem: (String, String, Int)? = nil
var closestBefore = Int(INT16_MAX)
for i in (index - 1).stride(to: 0, by: -1) {
if items[index].b == items[i].b {
closestBefore = index - i
foundItem = items[i]
break
}
}
var closestAfter = Int(INT16_MAX)
for i in index + 1 ..< items.count {
if items[index].b == items[i].b {
closestAfter = i - index
if closestAfter < closestBefore {
foundItem = items[i]
}
break
}
}
return foundItem
}
如果没有其他匹配项或者索引无效,则返回 nil,否则返回该项。
它只是向后搜索,直到找到匹配的项目,然后向前搜索,直到找到匹配的项目,然后返回最接近的项目。
最简单的是:
let startIndex = 7
if startIndex < items.count,
let nextIndex = items[startIndex+1..<items.endIndex].indexOf({ $0.b == items[startIndex].b }) {
print(items[nextIndex]) // => "("Item 14", "S", 17)\n"
}
这不是问题的完整答案,只是进行向前搜索的方法的示例。我意识到它与发布后的要求不符,但我将其作为部分示例。