1

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]]
2
  • How would you do it if these were just singular integers instead of arrays? Commented Feb 15, 2021 at 3:05
  • You are asking a different question in the body than in the title... Please edit to clarify which one you want. Commented Feb 15, 2021 at 3:09

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

this is extremely inefficient
1

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!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.