【问题标题】:Get index for closest value in array获取数组中最接近值的索引
【发布时间】:2022-01-15 18:23:09
【问题描述】:

使用此答案中的代码查找数组中最接近的值:https://stackoverflow.com/a/62159057

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

如何获取最接近而不是其值匹配的项目的索引?

【问题讨论】:

  • 数组排序了吗?这很重要。
  • @vadian 是的,数组是从低到高排序的。
  • 那就看看partitioningIndex(where:) in Swift Algorithms

标签: ios swift


【解决方案1】:

因为数组已排序,所以一个快速的解决方案是执行binary search

应该很容易修改this implementation(或同一帖子中的其他人)以适合您的目的。

【讨论】:

    【解决方案2】:

    firstIndex 解决了这个问题。不是很优雅,但很有效。

    func closestMatch(values: [Int], inputValue: Int) -> Int? {
        let match = values.reduce(values[0]) { abs($0-inputValue) < abs($1-inputValue) ? $0 : $1 }
        let index = values.firstIndex(where: {$0 == match})
        return index
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-30
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      • 2014-06-12
      相关资源
      最近更新 更多