2017-09-14 4 views
0

Heres何か私は自分自身を教えようとしています。私は、ネストされたindexArrayの要素のペアがnumberArray内の要素を指すようにしたい:入れ子にされていない配列のネストされた配列andices Swift

IOW:indexArray[[0,2],[3,4]]を有している場合、私は、ネストされた要素がnumberArray

の要素 #0numberArray#2と素子3,4に向かってポイントします
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

これは、あなたが簡単なmapで行うことができるもののように思える:

indexArray.map { $0.map { numberArray[$0] } } 
+0

Annnnnd私はまだ稼いでいる...笑! –

+1

それには何も問題ありません。私の提案: 'map'、' flatMap'、 'reduce'、' filter'メソッドを読んでください。彼らは本当に多くの状況で便利です! –

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"]] 
+0

それはクールだ!みんなありがとう!私はうまくいくものがあります。 –

関連する問題