如果数组被展平,我如何判断多维数组中项的索引是什么?

时间:2015-02-25 17:35:31

标签: arrays swift multidimensional-array

我有一个多维数组,其中包含最深层次的重复元素:

[
    ["taco","burrito"],
    ["chalupa","taco","bread"]
    ["pizza","lasagna"],
    ["pizza","taco","burrito"]
    ["salad","sandwich"],
    ["meat","turkey"]
    ["cups","chicken"],
    ["rabbit","taco", "chicken", "salad"]
]

我把这个阵容弄平了......

[
    "taco",
    "burrito",
    "chalupa",
    "taco",
    "bread",
    "pizza",
    "lasagna",
    etc...
]

我在多维数组中发现第二次出现“taco”这个词,并知道它的索引。

如何将该索引转换为展平数组中的索引?

所以在这个例子中它将是......

multiDimensionalArray[0][1][1]

=

flatArray[3]

3 个答案:

答案 0 :(得分:1)

首先,您需要一个函数将数组展平为一个字符串数组,以获得元素的真实索引。

public func flattenArray(array: Array<AnyObject>) -> Array<String> {
    var flattened: Array<String> = []
    for object: AnyObject in array {
        if object is Array<AnyObject> {
            for string in flattenArray(object as Array<AnyObject>) {
                flattened.append(string)
            }
        } else if object is String {
            flattened.append(object as String)
        }
    }
    return flattened
}

然后你需要编写一个函数来获取一定数量的数组中元素的索引

public func indexOfString(string: String, inArray array: Array<String>, occurance: Int = 1) -> Int? {

    var occurancesSoFar = 0
    var index: Int? = nil
    var currentIndex = 0

    for object in array {
        if object == string {
            if (++occurancesSoFar == occurance) {
                index = currentIndex
            }
        }
        ++currentIndex
    }

    return index
}

按顺序调用上述函数会给出正确的索引值:

let array = [
    ["taco","burrito"],
    ["chalupa","taco","bread"],
    ["pizza","lasagna"],
    ["pizza","taco","burrito"],
    ["salad","sandwich"],
    ["meat","turkey"],
    ["cups","chicken"],
    ["rabbit","taco", "chicken", "salad"]
]

let flat = flattenArray(array)

let index = indexOfString("taco", inArray: flat, occurance: 2)
println(index) // Optional(3)

使用这些方法,您可以将它们封装到一个名为

的函数中
func flattenAndFindElement(element: String, 
                           inArray array: Array<AnyObject>, 
                           atOccurrence occurrence: Int) -> Int?

或类似的东西。

希望有助于回答你的问题。

答案 1 :(得分:0)

Swift没有原生支持展平数组。您可以自己推出,或者可以使用具有展平方法的ExSwift。如果您成功展平了数组,那么显然您可以使用indexOfObject确定该值的索引。由于您有多个相同的对象,因此您可能需要使用indexesOfObjectsPassingTest,这将为您提供与您提供的测试匹配的所有索引的索引集。

答案 2 :(得分:0)

这是我最终做的事情:

func findFlattenedIndex(array: Array<Array<String>>, firstIndex: Int, secondIndex: Int) -> Int {

    var flatIndex = 0

    for (index1,secondTier) in enumerate(array) {
        for element in secondTier {
                if index1 != firstIndex{
                    println(element)
                    flatIndex += 1
                }
        }
        if index1 == firstIndex {
            flatIndex += secondIndex
            return flatIndex
            break
        }
    }
    return flatIndex
}

当然可以对其进行修改以处理任意数量的维度。

感谢大家的帮助。