如何在多维数组中快速找到项的索引?

如何在多维数组中快速找到项的索引?,第1张

概述假设我有这个数组: let a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 现在我想要这样的东西: public func indicesOf(x: Int, array: [[Int]]) -> (Int, Int) { ... } 所以我可以这样称呼它: indicesOf(7, array: a) // returns (2, 0) 当然, 假设我有这个数组:
let a = [[1,2,3],[4,5,6],[7,8,9]]

现在我想要这样的东西:

public func indicesOf(x: Int,array: [[Int]]) -> (Int,Int) {        ...    }

所以我可以这样称呼它:

indicesOf(7,array: a) // returns (2,0)

当然,我可以使用:

for i in 0..<array.count {    for j in 0..<array[i].count {        if array[i][j] == x {            return (i,j)        }    }}

但这甚至不是很接近!

我想要一种方法来做到这一点很快乐.我想也许我可以使用reduce或map?

您可以使用enumerate()和indexOf()稍微简化代码.
此函数还应返回一个可选元组,因为该元素
可能不存在于“矩阵”中.最后,你可以使它通用:
func indicesOf<T: Equatable>(x: T,array: [[T]]) -> (Int,Int)? {    for (i,row) in array.enumerate() {        if let j = row.indexOf(x) {            return (i,j)        }    }    return nil}

您还可以将其作为嵌套的Equatable数组的扩展
内容:

extension Array where Element : CollectionType,Element.Generator.Element : Equatable,Element.Index == Int {    func indicesOf(x: Element.Generator.Element) -> (Int,Int)? {        for (i,row) in self.enumerate() {            if let j = row.indexOf(x) {                return (i,j)            }        }        return nil    }}if let (i,j) = a.indicesOf(7) {    print(i,j)}

斯威夫特3:

extension Array where Element : Collection,Element.Iterator.Element : Equatable,Element.Index == Int {    func indices(of x: Element.Iterator.Element) -> (Int,row) in self.enumerated() {            if let j = row.index(of: x) {                return (i,j)            }        }        return nil    }}
总结

以上是内存溢出为你收集整理的如何在多维数组中快速找到项的索引?全部内容,希望文章能够帮你解决如何在多维数组中快速找到项的索引?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/web/1031175.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存