konya
konya

Reputation: 161

Find minimum first item in the given 2D array in Swift

I am trying to figure out how to find the smallest number in the given array's first element.

In the given array as follows, the smallest number in the first item in each array is 50 which is coming from [50,290]

var arr = [[100,155],[150,199],[180,220],[50,290],[400,590]]

Upvotes: 1

Views: 315

Answers (3)

Leo Dabus
Leo Dabus

Reputation: 236420

You can use min method and pass the first element of each array:

let min = arr.min(by: { ($0.first ?? .max) < ($1.first ?? .max) })?.first  // 50

Upvotes: 2

Yatin Batra
Yatin Batra

Reputation: 46

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)]

Modify it according to yours need may be it helpful for you!!

Upvotes: 1

aheze
aheze

Reputation: 30426

You could sort it using sorted(by:), checking the first element of each array in the array:

var arr = [[100,155],[150,199],[180,220],[50,290],[400,590]]

let sortedByFirst = arr.sorted { $0[0] < $1[0] }
print(sortedByFirst.first) /// Optional([50, 290])

Upvotes: 1

Related Questions