1

As we have support for Array to find max element using maxElement(), do we have any method using which we find max element in a 2D array Array<Array<Double>> in swift-2.0? Or do we need to write our own method?

1
  • If there is none, you could make an array that contains all the results for maxElement() for each "row" and then use maxElement on that Commented Oct 27, 2015 at 10:15

4 Answers 4

0

I don't know of any built in support for that but I suppose this is a simple enough solution

var matrix = [[3,5,4,6,7,],[9,2,6,8,3,5],[1,2,6,7,8,4]]

let max = matrix.maxElement({ (a, b) -> Bool in
    return a.maxElement() < b.maxElement()
})?.maxElement()

max is Optional(9) in this case

or you can use map for the same

let max2 = matrix.map({ (a) -> Int in
    return a.maxElement()!
}).maxElement()!

shorter version

let max3 = matrix.map({ $0.maxElement()!}).maxElement()!
Sign up to request clarification or add additional context in comments.

1 Comment

In the first case you call maxElement unpredicatable count of times and each time it iterates through all the array items. In the second and third case you iterate through all items twice wasting cpu resources and memory (because you don't apply any filters).
0
    import UIKit

var val= [
    [2, 4, 9],
    [3, 6, 0],
    [8, 7]
]

func raiseLowerValue(inout val: [[Int]]) {
    for row in 0..<image.count {
        for col in 0..<image[row].count {
           if image[row][col] < 5 {
              image[row][col] = 5
           }
        }
    }
}

by substituting "if" you can use by sort! or the other way.

Comments

0

The most optimized and universal solution:

struct CustomObject {
  var date: Date
}
let objectComparator = { (p1: CustomObject, p2: CustomObject) in
            p1.date > p2.date
        }
        let result = params.compactMap {
            $0.max(by: objectComparator)
        }
            .max(by: objectComparator)

After compactMap you get a flatten array which consists of max elements from the nested arrays. Then you apply max for the second time.

This code uses as little memory and cpu as possible.

Comments

0

You can use flatMap to convert to a 1D array, then take the max of that...

let max = matrix.flatMap { $0 }.max()

max is Optional(9)

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.