Reputation:
Heres something I'm trying to teach myself. I want a pair of elements in the nested indexArray
to point to elements inside the numberArray
:
IOW : IF indexArray
has [[0,2],[3,4]]
I want the nested elements to point towards element #0
and #2
in numberArray
and elements 3 and 4 in numberArray
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/
At first I thought about flattening the array, but that is NOT what I want.
Upvotes: 0
Views: 52
Reputation: 63271
A bit over engineered, but this is a pretty handy extension that comes in a lot of circumstances:
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"]]
Upvotes: 0
Reputation: 17050
This seems like something you can do with a simple map
:
indexArray.map { $0.map { numberArray[$0] } }
Upvotes: 2