gpt4 book ai didi

arrays - 在 Swift 中查找与条件匹配的数组中最接近的项目?

转载 作者:搜寻专家 更新时间:2023-11-01 06:40:28 24 4
gpt4 key购买 nike

当我引用数组中的某个项目时,我想找到另一个最接近它且符合特定条件(向前或向后)的项目。

例如,我有这个数组:

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 的想法吗?

最佳答案

使用高阶函数的优化解决方案:

 func closestMatch(values: [Int64], inputValue: Int64) -> Int64? {
return (values.reduce(values[0]) { abs($0-inputValue) < abs($1-inputValue) ? $0 : $1 })
}

Swift 不断改进每个版本以优化性能和效率。对于高阶函数,使用此实现可以更容易地找到值数组中最接近的匹配项。根据需要更改值的类型。

关于arrays - 在 Swift 中查找与条件匹配的数组中最接近的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36070464/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com