如何判断一个项目的多维数组的索引将是什么,如果数组被夷为平地? [英] How can I tell what the index of an item in a multidimensional array would be if the array were flattened?

查看:173
本文介绍了如何判断一个项目的多维数组的索引将是什么,如果数组被夷为平地?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有最深层次的一些重复的元素多维数组:

  [
    [塔科,卷饼],
    [chalupa,塔科,面包]
    [比萨,烤宽面条],
    [比萨,塔科,煎饼]
    [色拉,三明治]
    [肉,火鸡]
    [杯具,鸡],
    [兔子,塔科,鸡,色拉]
]

我已经夷为平地这个数组...

  [
    塔科
    卷饼,
    墨西哥拼盘,
    塔科
    面包,
    比萨,
    烤宽面条,
    等等...
]

我已经找到了词塔科的第二次出现多维数组中,并知道它的索引。

我如何扁平化数组中的索引转化为一个索引?

因此​​,在本实施例中这将是...

  multiDimensionalArray [0] [1] [1]=flatArray [3]


解决方案

下面是我落得这样做:

  FUNC findFlattenedIndex(数组:数组<数组<串GT;>中firstIndex:诠释,secondIndex的:int) -  GT; INT {    VAR flatIndex = 0    对于(索引1,secondTier)在历数(阵列){
        在secondTier {元素
                如果索引1!= firstIndex {
                    的println(元)
                    flatIndex + = 1
                }
        }
        如果索引1 == {firstIndex
            flatIndex + = secondIndex
            返回flatIndex
            打破
        }
    }
    返回flatIndex
}

当然,这可以被修改,以应对任何维数。

感谢大家的这方面的帮助。

I have a multidimensional array with some repeated elements in the deepest level:

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

I have flattened this array into...

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

I have found the second occurrence of the word "taco" in the multidimensional array and know its index.

How can I translate that index to an index in the flattened array?

So in this example it would be...

multiDimensionalArray[0][1][1]

=

flatArray[3]

解决方案

Here is what I ended up doing:

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
}

Of course this could be modified to deal with any number of dimensions.

Thanks for everyone's help with this.

这篇关于如何判断一个项目的多维数组的索引将是什么,如果数组被夷为平地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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