非嵌套数组Swift的嵌套数组和

时间:2017-09-14 17:52:48

标签: arrays swift

这是我尝试自学的东西。我希望嵌套indexArray中的一对元素指向numberArray中的元素:

IOW:如果indexArray[[0,2],[3,4]],我希望嵌套元素指向#0中的元素#2numberArray以及numberArray中的元素3和4 {1}}

    func findNumIndex(numberArray: [Int], indexArray: [[Int]]) -> Int {
       // Use the NESTED index elements to arrive at element index in numberArrray
    }

    findNumIndex(nums: [0,1,2,3,4,5,6,7,8,9], queries: [[0,1],[1,2],[3,4]])

   // We would look at index 0 and 1, index 1 and 2, index 3 and 4 and get the numbers/

起初我想过扁平化阵列,但这不是我想要的。

2 个答案:

答案 0 :(得分:2)

这似乎可以用简单的map

来完成
indexArray.map { $0.map { numberArray[$0] } }

答案 1 :(得分:0)

有点过度设计,但这是一个非常方便的扩展,在很多情况下出现:

extension RandomAccessCollection where Self.Index == Int {
    subscript<S: Sequence>(indices indices: S) -> [Self.Element]
        where S.Iterator.Element == Int {
        return indices.map{ self[$0] }
    }
}

let input = ["a", "b", "c", "d", "e"]
let queries = [[0, 1], [1, 2], [3, 4]]
let result = queries.map{ input[indices: $0] }

print(result) // => [["a", "b"], ["b", "c"], ["d", "e"]]