HansiOber
HansiOber

Reputation: 317

Swift: Get indexes of smallest items in 2-dimensional array

In Swift, is there a built-in method to get the indexes of the smallest items in a 2-dimensional array? Something like this pseudo code:

let array = [[1,4,8,3,9],[2,6,5,13,19]]

for item in 0...4 {
     2dimensionalIndex = array.smallest(item)  
}

Which then gives me the indices [0][0],[1][0],[0][3],[0][1],[1][2]?

Edit:

Background: I have a 2-dimensional array of CircularRegions and a user location. Since I can only register 20 regions for Geofencing, I compute the distance between the center of each region and the user location minus the radius of the region. Now I have a 2-dimensional array of distances. I want the indexes of the 20 smallest distances to register the regions.

Upvotes: 1

Views: 647

Answers (2)

Martin R
Martin R

Reputation: 539945

There is no "built-in" method. Here is a possible approach:

let array = [[1,4,8,3,9],[2,6,5,13,19]]

let sorted2DIndices = array.enumerate().flatMap {
        (i, row) in row.enumerate().map {
            (j, elem) in (i, j, elem)
        }
    }
    .sort { $0.2 < $1.2 }
    .map { (i, j, elem) in (i, j) }

print(sorted2DIndices)
// [(0, 0), (1, 0), (0, 3), (0, 1), (1, 2), (1, 1), (0, 2), (0, 4), (1, 3), (1, 4)]

The outer enumerate() enumerates the rows and the inner enumerate() the columns of the 2D array. Together with flatMap() and map(), this gives an array of (i, j, elem) triples where i is the row index and j the column index of elem.

This array is sorted according to the elements, and then mapped to an array of 2D indices.

sorted2DIndices[0] is the 2D index of the smallest element, etc. You can also get the indices of the four smallest elements with

let first4 = sorted2DIndices.prefix(4)
print(first4)
// [(0, 0), (1, 0), (0, 3), (0, 1)]

Upvotes: 4

Arsen
Arsen

Reputation: 10951

I think it's what you're looking for:

let array = [[1,4,8,3,9],[2,6,5,13,19]]
array.map { $0.indexOf($0.minElement()!)! }

Upvotes: 0

Related Questions