如何快速找到多维数组中项目的索引? [英] How to find the index of an item in a multidimensional array swiftily?

查看:256
本文介绍了如何快速找到多维数组中项目的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个数组:

let a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

现在我想要这样的东西:

Now I want something like this:

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)
        }
    }
}

但这还远远不够迅速!

我想要一种快速完成此操作的方法.我想也许我可以使用reducemap?

I want a way to do this which is swifty. I think maybe I can use reduce or map?

推荐答案

您可以使用enumerate()indexOf()稍微简化代码. 此外,该函数还应返回一个可选的元组,因为该元素 可能不存在于矩阵"中.最后,您可以使其通用:

You can simplify your code slightly with enumerate() and indexOf(). Also the function should return an optional tuple because the element might not be present in the "matrix". Finally, you can make it generic:

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的嵌套Array的扩展 元素:

You can also make it an extension for a nested Array of Equatable elements:

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, Int)? {
        for (i, row) in self.enumerated() {
            if let j = row.index(of: x) {
                return (i, j)
            }
        }
        return nil
    }
}

这篇关于如何快速找到多维数组中项目的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆