使用此答案中的代碼查找陣列中最接近的值: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 })
}
如何獲取與最接近而不是其值匹配的專案的索引?
uj5u.com熱心網友回復:
因為陣列是排序的,所以一個快速的解決方案是進行二分搜索。
應該很容易修改此實作(或同一篇文章中的其他實作)以適合您的目的。
uj5u.com熱心網友回復:
解決了它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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/413455.html
標籤:
上一篇:HTML基礎篇筆記
下一篇:this的系結(指向)規則
